Home >Backend Development >Python Tutorial >Can JSON Output Be an OrderedDict?
Can JSON be loaded into an OrderedDict?
In JSON serialization, OrderDicts can be utilized as inputs. However, a crucial question arises: can they also function as outputs? If so, what is the process?
JSON as an Output in OrderedDicts
Yes, OrderDicts can indeed serve as JSON outputs. This is achieved by specifying the object_pairs_hook argument within JSONDecoder. As mentioned in the documentation, this is the approach demonstrated in the following example:
>>> json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode('{"foo":1, "bar": 2}') OrderedDict([('foo', 1), ('bar', 2)]) >>>
Alternative JSON Output Parameters
For convenience, you can also pass this parameter directly to json.loads (without the need for a Decoder instance):
>>> 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 } >>>
Loading JSON Data into OrderedDicts
Similarly, JSON data can be loaded into OrderDicts using json.load in the same manner:
>>> data = json.load(open('config.json'), object_pairs_hook=OrderedDict)
The above is the detailed content of Can JSON Output Be an OrderedDict?. For more information, please follow other related articles on the PHP Chinese website!