Home >Backend Development >Python Tutorial >Can JSON Data Be Loaded into an OrderedDict, Maintaining Key Order?

Can JSON Data Be Loaded into an OrderedDict, Maintaining Key Order?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 01:48:10164browse

Can JSON Data Be Loaded into an OrderedDict, Maintaining Key Order?

Loading JSON into an OrderedDict

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn