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
Release: 2024-12-06 01:48:10
Original
193 people have browsed it

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)
Copy after login

This will output an OrderedDict with the keys in the same order as they appeared in the JSON data:

OrderedDict([('foo', 1), ('bar', 2)])
Copy after login

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template