原始文件内容:
{
"maskpolygonitem": {
"0": {
"boundingbox": "354.105 221.957 379.764 96.2241",
"label": "number",
"labelnum": 0,
"polygon": "3,6"
}
},
"channels": 3,
"height": 1080,
"width": 1920
}
修改并保存代码
#coding=utf-8
import os
import json
#获取目标文件夹的路径
filedir = r'j:\numberdata\mrcnnhik\test'
#获取文件夹中的文件名称列表
filenames=os.listdir(filedir)
#遍历文件名
for filename in filenames:
filepath = filedir '/' filename
# print(filepath)
after = []
# 打开文件取出数据并修改,然后存入变量
with open(filepath, 'r') as f:
data = json.load(f)
mask=data["maskpolygonitem"]
for zidian in mask:
print(type(zidian))
mask[zidian]["polygon"] = '354 221,355 310,729 318,733 236'
after = data
# 打开文件并覆盖写入修改后内容
with open(filepath, 'w') as f:
#结构化输出
data = json.dump(after, f,sort_keys=true, indent=4, separators=(',', ': '))
修改之后内容(仅修改了polygon)
{
"maskpolygonitem": {
"0": {
"boundingbox": "354.105 221.957 379.764 96.2241",
"label": "number",
"labelnum": 0,
"polygon": "354 221,355 310,729 318,733 236"
}
},
"channels": 3,
"height": 1080,
"width": 1920
}