You can indeed load JSON into an OrderedDict by using the object_pairs_hook argument of the JSON decoder. Here's how:
import json from collections import OrderedDict json_data = '{"foo":1, "bar": 2}' data = json.loads(json_data, object_pairs_hook=OrderedDict)
This will create an OrderedDict with the keys and values from the JSON string, preserving the order of the keys.
You can also use this approach with the json.load() function:
data = json.load(open('config.json'), object_pairs_hook=OrderedDict)
This will read the JSON data from a file and store it in an OrderedDict.
Keep in mind that the object_pairs_hook argument is only available in Python 2.6 and later.
The above is the detailed content of How Can I Load JSON Data into an OrderedDict in Python?. For more information, please follow other related articles on the PHP Chinese website!