Home > Backend Development > Python Tutorial > How Can I Load JSON Data into an OrderedDict in Python?

How Can I Load JSON Data into an OrderedDict in Python?

DDD
Release: 2024-12-13 00:53:10
Original
220 people have browsed it

How Can I Load JSON Data into an OrderedDict in Python?

Loading JSON into an OrderedDict

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template