Can I get JSON to load into an OrderedDict?

前端 未结 6 1022
别跟我提以往
别跟我提以往 2020-11-22 01:13

Ok so I can use an OrderedDict in json.dump. That is, an OrderedDict can be used as an input to JSON.

But can it be used as an output? If so how? In my

6条回答
  •  日久生厌
    2020-11-22 01:53

    Some great news! Since version 3.6 the cPython implementation has preserved the insertion order of dictionaries (https://mail.python.org/pipermail/python-dev/2016-September/146327.html). This means that the json library is now order preserving by default. Observe the difference in behaviour between python 3.5 and 3.6. The code:

    import json
    data = json.loads('{"foo":1, "bar":2, "fiddle":{"bar":2, "foo":1}}')
    print(json.dumps(data, indent=4))
    

    In py3.5 the resulting order is undefined:

    {
        "fiddle": {
            "bar": 2,
            "foo": 1
        },
        "bar": 2,
        "foo": 1
    }
    

    In the cPython implementation of python 3.6:

    {
        "foo": 1,
        "bar": 2,
        "fiddle": {
            "bar": 2,
            "foo": 1
        }
    }
    

    The really great news is that this has become a language specification as of python 3.7 (as opposed to an implementation detail of cPython 3.6+): https://mail.python.org/pipermail/python-dev/2017-December/151283.html

    So the answer to your question now becomes: upgrade to python 3.6! :)

提交回复
热议问题