Home > Backend Development > Python Tutorial > What are the methods for converting between dictionaries and JSON in Python?

What are the methods for converting between dictionaries and JSON in Python?

WBOY
Release: 2023-10-18 10:30:11
Original
1778 people have browsed it

What are the methods for converting between dictionaries and JSON in Python?

What are the mutual conversion methods between dictionary and JSON in Python?

As a very commonly used data structure, dictionary is widely used in Python. JSON (JavaScript Object Notation), as a lightweight data exchange format, is also widely used in network data transmission and storage. In Python, converting between dictionaries and JSON is a common operation. This article will introduce several commonly used methods and attach corresponding code examples.

Method 1: Use the dumps() function and loads() function of the json module

The json module is a module in the Python standard library used to process JSON data. Among them, the dumps() function is used to convert Python objects into JSON strings, and the loads() function is used to convert JSON strings into Python objects.

The following is an example to convert a dictionary to a JSON string and convert a JSON string back to a dictionary:

import json

# 将字典转换为JSON字符串
my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
json_str = json.dumps(my_dict)

print(json_str)  # 输出:{"name": "Tom", "age": 20, "gender": "male"}

# 将JSON字符串转换为字典
new_dict = json.loads(json_str)

print(new_dict)  # 输出:{'name': 'Tom', 'age': 20, 'gender': 'male'}
Copy after login

Method 2: Use the dump() function and load() of the json module Function

In addition to the above dumps() function and loads() function, the json module also provides the dump() function and load() function for writing Python objects directly to files or reading from files. Get JSON data.

The following is an example of writing a dictionary to a JSON file and reading a dictionary from a JSON file:

import json

# 将字典写入JSON文件
my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
with open('data.json', 'w') as f:
    json.dump(my_dict, f)

# 从JSON文件中读取字典
with open('data.json', 'r') as f:
    new_dict = json.load(f)

print(new_dict)  # 输出:{'name': 'Tom', 'age': 20, 'gender': 'male'}
Copy after login

Method 3: Use the json.JSONEncoder and json.JSONDecoder classes in the json module Subclasses

In addition to the above function methods, we can also implement conversion between dictionaries and JSON by customizing subclasses of the json.JSONEncoder and json.JSONDecoder classes. By inheriting these two classes and overriding the relevant methods, we can customize the dictionary conversion behavior.

The following is an example of customizing subclasses of the JSONEncoder and JSONDecoder classes to convert between dictionaries and JSON:

import json

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, dict):
            return json.JSONEncoder.default(self, obj)
        return obj.__dict__

class MyDecoder(json.JSONDecoder):
    def __init__(self):
        json.JSONDecoder.__init__(self, object_hook=self.dict_to_object)

    def dict_to_object(self, d):
        if '__class__' in d:
            class_name = d.pop('__class__')
            module_name = d.pop('__module__')
            module = __import__(module_name)
            class_ = getattr(module, class_name)
            args = dict((key, value) for key, value in d.items())
            instance = class_(**args)
        else:
            instance = d
        return instance

# 将字典转换为JSON字符串
my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
json_str = json.dumps(my_dict, cls=MyEncoder)

print(json_str)  # 输出:{"name": "Tom", "age": 20, "gender": "male"}

# 将JSON字符串转换为字典
new_dict = json.loads(json_str, cls=MyDecoder)

print(new_dict)  # 输出:{'name': 'Tom', 'age': 20, 'gender': 'male'}
Copy after login

The above are several commonly used methods for implementing Python dictionaries Conversion to and from JSON. According to actual needs, choose the appropriate method to use, which can easily handle data conversion between dictionary and JSON.

The above is the detailed content of What are the methods for converting between dictionaries and JSON in Python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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