簡體   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