当前位置: 代码迷 >> 综合 >> python更新json文件
  详细解决方案

python更新json文件

热度:95   发布时间:2024-02-06 23:52:19.0

有json文件如下:

{"info": 
[{"platform": 1, "toptype": 1, "flag": 1}, {"platform": 1, "toptype": 2, "flag": 1}, 
{"platform": 1, "toptype": 3, "flag": 1}, {"platform": 1, "toptype": 4, "flag": 1}, 
{"platform": 2, "toptype": 1, "flag": 1}, {"platform": 2, "toptype": 2, "flag": 1}, 
{"platform": 2, "toptype": 3, "flag": 1}, {"platform": 2, "toptype": 4, "flag": 1}, 
{"platform": 3, "toptype": 1, "flag": 1}, {"platform": 3, "toptype": 2, "flag": 1}, 
{"platform": 3, "toptype": 3, "flag": 1}, {"platform": 3, "toptype": 4, "flag": 1}
]}

我要把flag更新一下:

import json
import ospath = os.path.abspath('read.json')
platform_list = [1,2,3
]toptype_list = [1,2,3,4
]for platform in platform_list:for toptype in toptype_list:with open(path, 'r+') as f:item = json.load(f)infos = item['info']for i,info in enumerate(infos):if info['platform'] == platform and info['toptype'] == toptype and info['flag'] == 1:info['flag'] = if.seek(0)f.write(json.dumps(item))f.truncate()

于是json文件变成了:

{"info": 
[{"platform": 1, "toptype": 1, "flag": 0}, {"platform": 1, "toptype": 2, "flag": 1},{"platform": 1, "toptype": 3, "flag": 2}, {"platform": 1, "toptype": 4, "flag": 3},{"platform": 2, "toptype": 1, "flag": 4}, {"platform": 2, "toptype": 2, "flag": 5},{"platform": 2, "toptype": 3, "flag": 6}, {"platform": 2, "toptype": 4, "flag": 7},{"platform": 3, "toptype": 1, "flag": 8}, {"platform": 3, "toptype": 2, "flag": 9},{"platform": 3, "toptype": 3, "flag": 10}, {"platform": 3, "toptype": 4, "flag": 11}
]}

以上