问题描述
我正在尝试合并两个 json 文件,但我正在尝试将来自 file2 的时间戳附加到 file1.please 指南中的相应帧号。
JSON_FILE1
{"frameNumber":1,"classifications":[],"objects":[{"featureId":"ckotybs4v00033b68edh8a6o5","schemaId":"ckoto8fzm16gj0y7uesrd0nzt","title":"Person 1","value":"person_1","color":"#1CE6FF","keyframe":true,"bBox":{"top":157,"left":581,"height":390,"width":297},"classifications":[]}]}
{"frameNumber":2,"keyframe":false,"height":390.36,"width":297.16},"classifications":[]}]}
{"frameNumber":3,"height":390.72,"width":297.32},"classifications":[]}]}
{"frameNumber":4,"height":391.08,"width":297.48},"classifications":[]}]}
{"frameNumber":5,"height":391.44,"width":297.64},"classifications":[]}]}
JSON_FILE2
{
"frame1": "0:0:0:66","frame2": "0:0:0:100","frame3": "0:0:0:133","frame4": "0:0:0:166","frame5": "0:0:0:200"
}
预期输出:
{"frameNumber":1,"frame1": "0:0:0:66","frame2": "0:0:0:10,"frame3": "0:0:0:133,"frame5": "0:0:0:200","classification
我尝试过这种方式,但无法实现。
import json
import glob
result = []
for f in glob.glob("*.json"):
with open(f,"rb") as infile:
result.append(json.load(infile))
with open("merged_file.json","wb") as outfile:
json.dump(result,outfile)
解决方法
一个正确的 .json 需要一对 []
而不是你可以 json.load
它,迭代每一行并像下面一样做同样的事情,但无论如何:
最简单的解决方案是将每一行都转为 dict
,如果帧号匹配,则添加时间戳并将其写回。
def fuse(file1,file2,nTargetPath):
with open(nTargetPath,"wb") as tTargetFile:
with open(file1,"rb") as tSourceFileA:
for tLineA in tSourceFileA.readlines():
tDictA = json.loads(tLineA) #loads dict from a string
tKey = "frame"+tDictA["frameNumber"] #searching the correct entry but why not name this timestampX
with open(file2,"rb") as tSourceFileB:
for tLineB in tSourceFileB.readlines():
tDictB = json.loads(tLineB )
if tKey in tDictB:
tDictA[tKey] = tDictB[tKey]
break #cause there is only one timestamp
tTargetFile.write(json.dumps(tDictA)+'\n')
此代码可以通过改进文件访问来轻松更新,例如当您知道 file2 中时间戳的键每次都与 file1 中的同一行等时。
,如前所述,一个文件是ndjson
,另一个文件是json
。您需要实现一些逻辑来将 json
添加到 ndjson
# https://pypi.org/project/ndjson/
# pip install ndjson
import ndjson
import json
with open('path/to/file/im_a_ndjson.ndjson') as infile:
ndjson_object = ndjson.load(infile)
with open('path/to/file/json_file2.json') as infile:
dict_object = json.load(infile)
print(type(ndjson_object[0]['frameNumber']))
# output: <class 'int'>
for key in dict_object:
# int needed as you can see above
framenumber = int(key.strip('frame'))
# find the matching ndjson object
for ndjs in ndjson_object:
if ndjs['frameNumber'] == framenumber:
# add the key/value pair
ndjs[key] = dict_object[key]
# we can break as we've found it
break
with open('path/to/file/new_ndjson.ndjson','w') as outfile:
ndjson.dump(ndjson_object,outfile)