kiyasuの日記

ハッピーうれピーよろしく哀愁

python json 変更

jsonの中に100項目くらいになるリストがあり、その中の特定のオブジェクトの内容を変えたい

{
    "list": [
        {
            "filePath": "C:/proj/test01.jpg",
            "id" : ....
        ....
        },
        {
            "filePath": "C:/proj/test02.jpg",
            "id" : ....
        ....
        },
...
    ]
}

みたいな。これの全部のfilePathを変えたい。

stackoverflow.com

これをほぼそのまま

import json
i = 1

path = "C:/proj/product"

with open('file.json','r', encoding='utf-8') as f:
    data = json.load(f)

for item in data['list']:
    fullpath = path + ' (' + str(i)+ ').jpg'
    item['filePath'] = fullpath
    i = i + 1


with open('new_data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f)

という感じです