Loading JSON into an OrderedDict
In JSON, data is stored in key-value pairs. The order of these pairs is not guaranteed. However, in certain scenarios, maintaining the order of keys is crucial. The question arises: can JSON be loaded into an ordered dictionary (OrderedDict)?
Solution with object_pairs_hook
Yes, JSON can be loaded into an OrderedDict. This is achieved by specifying the object_pairs_hook argument to the JSONDecoder constructor. The object_pairs_hook argument takes a function that is called for each pair of keys and values in the JSON object. This function can return an ordered dictionary, ensuring the order of the keys is preserved. Below is an example:
import json from collections import OrderedDict data = json.loads('{"foo":1, "bar": 2}', object_pairs_hook=OrderedDict) print(json.dumps(data, indent=4))
Output:
{ "foo": 1, "bar": 2 }
This works because the object_pairs_hook function returns an OrderedDict object, which maintains the order of the keys.
Alternative Using json.load
The same approach can be applied to the json.load function:
data = json.load(open('config.json'), object_pairs_hook=OrderedDict)
The above is the detailed content of Can JSON be Loaded into an OrderedDict to Preserve Key Order?. For more information, please follow other related articles on the PHP Chinese website!