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

Can JSON be Loaded into a Python OrderedDict to Preserve Key Order?

Linda Hamilton
Release: 2024-12-02 13:45:12
Original
646 people have browsed it

Can JSON be Loaded into a Python OrderedDict to Preserve Key Order?

Loading JSON into an OrderedDict

In Python, an OrderedDict maintains the order of its keys, unlike a regular dictionary. While it's possible to dump an OrderedDict into JSON using json.dump, can we also load JSON back into an OrderedDict to preserve the original key ordering?

Loading JSON into an OrderedDict

To load JSON into an OrderedDict, use the object_pairs_hook argument in the JSONDecoder class or in json.loads and json.load. This argument specifies a function that will be called on each pair of keys and values in the JSON object as they are being loaded.

For example, to load JSON into an OrderedDict using the JSONDecoder class:

import json
from collections import OrderedDict

decoder = json.JSONDecoder(object_pairs_hook=collections.OrderedDict)
data = decoder.decode('{"foo": 1, "bar": 2}')
Copy after login

You can also pass the object_pairs_hook argument directly to json.loads:

import json
from collections import OrderedDict

data = json.loads('{"foo": 1, "bar": 2}', object_pairs_hook=Collections.OrderedDict)
Copy after login

Or when opening a JSON file:

import json
from collections import OrderedDict

with open('config.json') as f:
    data = json.load(f, object_pairs_hook=OrderedDict)
Copy after login

This will load the JSON data into an OrderedDict while maintaining the original order of the keys.

The above is the detailed content of Can JSON be Loaded into a Python 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