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