繁体   English   中英

如何在python 2.7中比较两个JSON文件?

[英]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

你需要像这样 您是否尝试过JSON工具

pip install json_tools

然后从命令行尝试

json diff file1.json file2.json > output.json

然后将输出用于进一步处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM