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

0 投票
2 回答
1845 浏览
提问于 2025-04-21 08:29

我有两个文件,里面都是一些JSON对象。第一个文件是用Python的一个模块xmltodict把XML文件转换过来的。把XML转换成字典后,我又用json.dumps把它们变成JSON对象。第二个文件里则是通过HTTP GET请求得到的一堆JSON对象。我的目标是把第一个文件和第二个文件进行比较,如果第一个文件里的某个JSON对象的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

2 个回答

-1

你需要类似于这个的东西吗?你试过JSON工具吗?

pip install json_tools

然后在命令行中试试这个

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

接着可以用输出的结果进行进一步处理。

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

撰写回答