Problem Origin
JSON object, A, b
' {"ROAD": [{"id": 123}, {"Name": "No1"}]} ' '{' ROAD ': [{' Name ': ' No1 '}, {' id ': 123}]}'
features : A/b corresponds to the key value of the key in the Python object--The list contains the same dictionary elements, but the only difference is the order is different . If the order is omitted, how to determine whether two JSON is equal. Because the dictionaries themselves are sorted by their keystrokes, the lists are sorted in the order in which they are added, and if you sort the dictionary elements in the list, you can sort them easily. If the list is a normal element (not a dictionary), the list can be sorted by a combination of list (set ()), and if the dictionary element in the list cannot use the list (set ()) combination, look at the hint:
>>> a = [{' A ': 1, ' B ': 2}, {' C ':3}]>>> a[{' a ': 1, ' B ': 2}, {' C ': 3}]>>> B = Set (a) Traceback (most Recent: File "<pyshell#2>", line 1, in <module> B = Set (a) typeerror:unhashable type: ' dic T
Tip A dictionary is a type that is not hashed (ordinary non-dictionary elements are hashed to make it easy to sequence).
So the nature of the problem is how to sort the dictionary elements in the list.
sort the dictionary elements in a list
Fortunately, the list has sorted function, try
>>> p = [{' B ': 2}, {' A ': 1, ' C ': 3}]>>> q = [{' A ': 1, ' C ': 3}, {' B ': 2}]>>> p[{' B ': 2}, {' A ': 1 , ' C ': 3}]>>> q[{' A ': 1, ' C ': 3}, {' B ': 2}]>>> pp = sorted (p) >>> qq = sorted (q) >>> pp[ {' B ': 2}, {' A ': 1, ' C ': 3}]>>> qq[{' B ': 2}, {' A ': 1, ' C ': 3}]>>> pp = = qqtrue>>> p = = Qfalse
As can be seen, OK, and you can see the principle of sorting is the number of elements.
Compare JSON (ignore the order of dictionaries in the list)
ImportJSONdefCompare_json (A, b): AA=json.loads (a) BB=Json.loads (b) len_a=len (aa) Len_b=Len (BB)ifLen_a! =Len_b:returnFalseElse: forKeyinchAA:if notBb.has_key (key):returnFalseElse: ifSorted (Aa[key])! =sorted (Bb[key]):returnFalsereturnTrueif __name__=="__main__": A='{"ROAD": [{"id": 123}, {"Name": "No1"}]}'b='{"ROAD": [{"Name": "No1"}, {"id": 123}]}' PrintCompare_json (A, B)
details : When writing the JSON format yourself, a = "{' Road ': 1}" Json.loads (a) error, must be written as a = ' {"road:1} '" Single quote Out "
Python sorts the dictionary elements in the list