Question:
Is it possible to load JSON data into an OrderedDict, preserving the original order of keys?
Answer:
Yes, it is possible to load JSON into an OrderedDict using the object_pairs_hook argument of the JSONDecoder class. This argument specifies the function to be called to construct the object from the decoded JSON data.
By passing collections.OrderedDict as the object_pairs_hook argument, you can ensure that the resulting object is an OrderedDict, preserving the order of the keys in the JSON data.
Here's how you can use this argument with json.JSONDecoder:
decoder = json.JSONDecoder(object_pairs_hook=collections.OrderedDict) data = decoder.decode('{"foo":1, "bar": 2}') print(data)
This will output an OrderedDict with the keys in the same order as they appeared in the JSON data:
OrderedDict([('foo', 1), ('bar', 2)])
You can also use this argument with json.loads to achieve the same result:
import json from collections import OrderedDict data = json.loads('{"foo":1, "bar": 2}', object_pairs_hook=OrderedDict) print(data)
Finally, you can use this argument with json.load to load data from a file into an OrderedDict:
data = json.load(open('config.json'), object_pairs_hook=OrderedDict)
The above is the detailed content of Can JSON Data Be Loaded into an OrderedDict, Maintaining Key Order?. For more information, please follow other related articles on the PHP Chinese website!