我有两个文件填充了JSON对象。一个是使用Python模块xmltodict
从XML转换而来的。一旦我将所有XML作为dicts,我就使用json.dumps
将它们转换为JSON对象。在另一个文件中,我有一堆来自HTTP GET请求的JSON对象。我的目标是比较第一个文件和第二个文件,如果第一个文件有一个JSON对象,其中name
键与第二个文件中的任何对象name
键都不匹配,那么它会得到添加到第二个文件。我的问题是,是否有人建议如何做到这一点?或者我只需要求助于冷硬解析?下面的伪代码就是我目前的想法:
postFlag = 0
for obj1 in file1: #for each JSON object in first file
for obj2 in file2: #compare to each JSON object in second file.
if obj1.name == obj2.name: #if they match,
postFlag = 0 #prepare to not post
break #and go to next JSON object in file1
else: #if they dont match
postFlag = 1 #prepare to post
if postFlag == 1: #if went through all obj2 and no match, then add to file2
add obj1 to file2
答案 0 :(得分:0)
考虑以下代码
dict_1 = { o.name: o for o in file1 } # Construct a dict of name:object
# Use set operation to find the name not in file2
for need_insert in set(dict_1) - set([ o.name for o in file2 ]):
add dict1[need_insert] to file2
答案 1 :(得分:-1)
您需要this之类的内容吗?你试过JSON tools吗?
pip install json_tools
并从命令行尝试
json diff file1.json file2.json > output.json
然后使用输出进行进一步处理。