Loading JSON into an OrderedDict
In Python, an OrderedDict maintains the order of its keys, unlike a regular dictionary. While it's possible to dump an OrderedDict into JSON using json.dump, can we also load JSON back into an OrderedDict to preserve the original key ordering?
Loading JSON into an OrderedDict
To load JSON into an OrderedDict, use the object_pairs_hook argument in the JSONDecoder class or in json.loads and json.load. This argument specifies a function that will be called on each pair of keys and values in the JSON object as they are being loaded.
For example, to load JSON into an OrderedDict using the JSONDecoder class:
import json from collections import OrderedDict decoder = json.JSONDecoder(object_pairs_hook=collections.OrderedDict) data = decoder.decode('{"foo": 1, "bar": 2}')
You can also pass the object_pairs_hook argument directly to json.loads:
import json from collections import OrderedDict data = json.loads('{"foo": 1, "bar": 2}', object_pairs_hook=Collections.OrderedDict)
Or when opening a JSON file:
import json from collections import OrderedDict with open('config.json') as f: data = json.load(f, object_pairs_hook=OrderedDict)
This will load the JSON data into an OrderedDict while maintaining the original order of the keys.
The above is the detailed content of Can JSON be Loaded into a Python OrderedDict to Preserve Key Order?. For more information, please follow other related articles on the PHP Chinese website!