Since json.dump
can write OrderDict
, I know that OrderDict
can be used as JSON's input.
What should I do if I want to write output?
json python load ordereddictionary
This is possible by using the factor object_pairs_hook
in
>>> json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode('{"foo":1, "bar": 2}')
OrderedDict([('foo', 1), ('bar', 2)])
>>>
Now pass this parameter to json.loads
>>> import json
>>> from collections import OrderedDict
>>> data = json.loads('{"foo":1, "bar": 2}', object_pairs_hook=OrderedDict)
>>> print json.dumps(data, indent=4)
{
"foo": 1,
"bar": 2
}
>>>
A similar approach can be used with json.load.
>>> data = json.load(open('config.json'), object_pairs_hook=OrderedDict)
© 2024 OneMinuteCode. All rights reserved.