Home > Backend Development > Python Tutorial > Can JSON be Loaded into an OrderedDict to Preserve Key Order?

Can JSON be Loaded into an OrderedDict to Preserve Key Order?

Mary-Kate Olsen
Release: 2024-12-06 22:19:12
Original
806 people have browsed it

Can JSON be Loaded into an OrderedDict to Preserve Key Order?

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

Output:

{
    "foo": 1,
    "bar": 2
}
Copy after login

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

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!

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