首页 > 解决方案 > 在python中将json文件与comon键合并

问题描述

我有一些 json 文件

框架1.json:

{"annotation": {"folder": "lab_img", "filename": "frame1.jpg", "size": {"width": "1280", "height": "720", "depth": "3"}, "segmented": "0", "object": {"name": "person1", "pose": "Unspecified", "truncated": "0", "difficult": "0", "bndbox": {"xmin": "553", "ymin": "147", "xmax": "894", "ymax": "552"}}}}

时间戳

{"frame1": "0:0:0:66", "frame2": "0:0:0:100", "frame3": "0:0:0:133", "frame4": "0:0:0:166"}

预期的o/p:output.json

{"annotation": {"folder": "lab_img", "filename": "frame1.jpg", "size": {"width": "1280", "height": "720", "depth": "3"}, "segmented": "0", "object": {"name": "person1", "pose": "Unspecified", "truncated": "0", "difficult": "0", "bndbox": {"xmin": "553", "ymin": "147", "xmax": "894", "ymax": "552","frame1": "0:0:0:66"}}}}

我需要在 python 中迭代超过 10k 个 json 文件,因为我是 python 的新手,我尝试过这种方法:

import json

with open('C:\\Users\\frame1.json') as infile:
    json_object = json.load(infile)


with open('C:\\Users\\time_stamp.json') as infile:
    dict_object = json.load(infile)

for key in dict_object:

    framenumber = int(key.strip('frame'))
   
    for ndjs in json_object:
        if ndjs['frame'] == framenumber:
            # add the key/value pair
            ndjs[key] = dict_object[key]
            # we can break as we've found it
            break

标签: python

解决方案


dic1={"annotation": {"folder": "lab_img", "filename": "frame1.jpg", "size": {"width": "1280", "height": "720", "depth": "3"}, "segmented": "0", "object": {"name": "person1", "pose": "Unspecified", "truncated": "0", "difficult": "0", "bndbox": {"xmin": "553", "ymin": "147", "xmax": "894", "ymax": "552"}}}}
dic2={"frame1": "0:0:0:66", "frame2": "0:0:0:100", "frame3": "0:0:0:133", "frame4": "0:0:0:166"}

for i,j in dic2.items():
    dic1["annotation"]["object"]["bndbox"].__setitem__(i,j)
    break
print(dic1)

推荐阅读