[英]How to compare two JSON files and form an single JSON file in python
[英]How to compare two JSON files in python 2.7?
我有两个充满JSON对象的文件。 一种是使用Python模块xmltodict
从XML转换的。 一旦将所有XML作为字典,就可以使用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
考虑以下代码
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.