2012-06-21 54 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