Why json.dumps() in python 3 return a different value of python 2? [duplicate] Why json.dumps() in python 3 return a different value of python 2? [duplicate] json json

Why json.dumps() in python 3 return a different value of python 2? [duplicate]


In Python before 3.6, the dictionary keys are not ordered. So in Python 3.6, the keys maintain the order of their insertion (or in the case of a dictionary literal, how they appear in the literal). The Python 2.7 dictionary is unordered, so the looping order does not necessarily match insertion order.

If you were to reload the json dictionary in both cases, it would still be equal (dictionary equality does not depend on order).

So there is no error here. The difference is because of how dictionaries are ordered in different Python versions.

json.dump and json.dumps write the key-value pairs out in the dictionary looping order. So in order to have consistent looping order, it would be best to use the collections.OrderedDict type in order to achieve consistent ordering. If you are calling json.load to get dictionaries, you would also need to use json.loads(text, object_hook=OrderedDict), which will then maintain ordering.

There is no trivial way to make Python 3 dictionaries use a Python 2 ordering, so moving both 2 and 3 code bases to use OrderedDict is a more maintainable solution.