14

以下の 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
   }
}
4

2 に答える 2

13

通常の比較は正常に機能しているようです

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    
于 2012-06-21T15:43:54.993 に答える
4

これらは有効な 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)
于 2012-06-21T15:40:39.507 に答える