How do I keep the JSON key order fixed with Python 3 json.dumps?

前端 未结 2 1028
予麋鹿
予麋鹿 2021-02-08 19:18

I\'ve noticed some strange behavior on Python 3\'s implementation of json.dumps, namely the key order changes every time I dump the same object from execution to ex

相关标签:
2条回答
  • 2021-02-08 19:30

    The story behind this behavior is this vulnerability. To prevent it, same hash codes on one PC should be different on another one.

    Python 2 has probably disabled this behavior (hash randomizing) by default because of compatibility, as this would for example break doctests. Python 3 probably (an assumption) has not needed the compability.

    0 讨论(0)
  • 2021-02-08 19:49

    Python dictionaries and JSON objects are unordered. You can ask json.dumps() to sort the keys in the output; this is meant to ease testing. Use the sort_keys parameter to True:

    print(json.dumps(data, indent=2, sort_keys=True))
    

    See Why is the order in Python dictionaries and sets arbitrary? as to why you see a different order each time.

    You can set the PYTHONHASHSEED environment variable to an integer value to 'lock' the dictionary order; use this only to run tests and not in production, as the whole point of hash randomisation is to prevent an attacker from trivially DOS-ing your program.

    0 讨论(0)
提交回复
热议问题