如何比较下面python中的2个json对象是示例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
}
}
Run Code Online (Sandbox Code Playgroud)
def*_*fuz 12
似乎通常的比较工作正常
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
Run Code Online (Sandbox Code Playgroud)
这些不是有效的 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)
Run Code Online (Sandbox Code Playgroud)