如何在python中比较2个json
下面是示例json,说明如何在python中比较2个json对象如何在python中比较2个json,python,Python,下面是示例json,说明如何在python中比较2个json对象 sample_json1={ { "globalControlId": 72, "value": 0, "controlId": 2 }, { "globalControlId": 77, "value": 3, "controlId": 7 } } sample_json2={ { "global
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
}
}
这些是无效的JSON/Python对象,因为数组/列表文本位于
[]
而不是{}
中:
更新:要比较字典列表(对象的序列化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)
看来,通常的比较工作正常
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
你能解释一下为什么
如果sample\u json1==sample\u json2:
不够吗???你写的“json”示例是无效的。如果需要任何帮助,您必须向我们提供更多的上下文/工作代码。如果顺序发生变化,这将不起作用。例如,下面的示例失败sample_json1=[{“globalControlId”:72,“value”:0,“controlId”:2},{“globalControlId”:77,“value”:3,“controlId”:7}]sample_json2=[{“globalControlId”:77,“值”:3,“控制ID”:7},{“globalControlId”:72,“值”:0,“控制ID”:2}]比较应该是成功的,即使订单发生变化,请在此帮助我根据更新comments@zochhuana另一个解决方案处理嵌套的JSON吗?即使它处理嵌套的JSON,我也不会指望它。如果你需要进行深入的比较,google中的一个顶级链接是