2012-06-21 81 views
12

如何比較下面的python中的2個json對象是樣本json。如何比較python中的2個json

sample_json1={ 
    { 
     "globalControlId": 72, 
     "value": 0, 
     "controlId": 2 
    }, 
    { 
     "globalControlId": 77, 
     "value": 3, 
     "controlId": 7 
    } 
} 

sample_json2={ 
    { 
     "globalControlId": 72, 
     "value": 0, 
     "controlId": 2 
    }, 
    { 
     "globalControlId": 77, 
     "value": 3, 
     "controlId": 7 
    } 
} 
+0

你能解釋爲什麼'如果sample_json1 == sample_json2:'會不夠? – Aprillion

+2

你寫的「json」樣本無效。如果您需要任何幫助,您必須給我們更多的上下文/工作代碼。 – Wilduck

回答

3

這些都不是有效的JSON/Python對象,因爲陣列/列表文字是內部的[]代替{}

UPDATE:比較字典的列表(對象的串行化JSON陣列),而忽略列表項的順序,列出需分類或轉換爲集

sample_json1=[{"globalControlId": 72, "value": 0, "controlId": 2}, 
       {"globalControlId": 77, "value": 3, "controlId": 7}] 
sample_json2=[{"globalControlId": 77, "value": 3, "controlId": 7}, 
       {"globalControlId": 77, "value": 3, "controlId": 7}, # duplicity 
       {"globalControlId": 72, "value": 0, "controlId": 2}] 

# dictionaries are unhashable, let's convert to strings for sorting 
sorted_1 = sorted([repr(x) for x in sample_json1]) 
sorted_2 = sorted([repr(x) for x in sample_json2]) 
print(sorted_1 == sorted_2) 

# in case the dictionaries are all unique or you don't care about duplicities, 
# sets should be faster than sorting 
set_1 = set(repr(x) for x in sample_json1) 
set_2 = set(repr(x) for x in sample_json2) 
print(set_1 == set_2) 
+0

如果爲了使下面的例子失敗 – santosh

+0

sample_json1 = [{ 「globalControlId」:72, 「值」:0, 「控件ID」:2}改變示例中,這不會工作, { 「globalControlId」:77, 「值」:3, 「控件ID」:7}] sample_json2 = [ { 「globalControlId」:77, 「值」:3, 「控件ID」:7}, { 「globalControlId」:72, 「價值」:0, 「controlId」:2}] – santosh

+0

比較應該是成功的即使訂單變更請幫我在這裏 – santosh

11

看來,通常的比較正常工作

import json 
x = json.loads("""[ 
    { 
     "globalControlId": 72, 
     "value": 0, 
     "controlId": 2 
    }, 
    { 
     "globalControlId": 77, 
     "value": 3, 
     "controlId": 7 
    } 
]""") 

y = json.loads("""[{"value": 0, "globalControlId": 72,"controlId": 2}, {"globalControlId": 77, "value": 3, "controlId": 7 }]""") 

x == y # result: True  
+0

,謝謝:) – ashim888