python--解析多层json

时间:2024-10-21 08:26:19

原始文件内容:

{
    "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
}