Python 简明教程

Python - JSON

JSON in Python

Python 中的 JSON 是一种流行的数据格式,用于系统之间的数据交换。 json 模块提供用于处理 JSON 数据的函数,使您可以将 Python 对象序列化成 JSON 字符串,并将 JSON 字符串反序列化回 Python 对象。

JSON in Python is a popular data format used for data exchange between systems. The json module provides functions to work with JSON data, allowing you to serialize Python objects into JSON strings and deserialize JSON strings back into Python objects.

JSON Serialization

JSON 序列化是将 Python 对象转换为 JSON 格式的过程。这对于以易于传输或存储的格式保存数据很有用,之后可以将其重新构建成其原始形式。

JSON serialization is the process of converting a Python object into a JSON format. This is useful for saving data in a format that can be easily transmitted or stored, and later reconstructed back into its original form.

Python 提供了 json 模块来处理 JSON 序列化和反序列化。我们可以在此模块中使用 json.dumps() 方法进行序列化。

Python provides the json module to handle JSON serialization and deserialization. We can use the json.dumps() method for serialization in this module.

您可以将以下 Python 对象类型序列化为 JSON 字符串 −

You can serialize the following Python object types into JSON strings −

  1. dict

  2. list

  3. tuple

  4. str

  5. int

  6. float

  7. bool

  8. None

Example

以下是有关如何将 Python 字典序列化为 JSON 字符串的基本示例 −

Following a basic example of how to serialize a Python dictionary into a JSON string −

import json

# Python dictionary
data = {"name": "Alice", "age": 30, "city": "New York"}

# Serialize to JSON string
json_string = json.dumps(data)
print(json_string)

它将生成如下输出:

It will produce the following output −

{"name": "Alice", "age": 30, "city": "New York"}

JSON Deserialization

JSON 反序列化是将 JSON 字符串转换回 Python 对象的过程。这对于读取和处理以 JSON 格式传输或存储的数据非常重要。

JSON deserialization is the process of converting a JSON string back into a Python object. This is essential for reading and processing data that has been transmitted or stored in JSON format.

在 Python 中,我们可以使用 json.loads() 方法从 string 中反序列化 JSON 数据,并使用 json.load() 方法从 file 中反序列化 JSON 数据。

In Python, we can use json.loads() method to deserialize JSON data from a string, and json.load() method to deserialize JSON data from a file.

Example: Deserialize JSON string to Python object

在以下示例中,我们使用 json.loads() 方法将 JSON 字符串反序列化为 Python 字典:

In the following example we are deserializing a JSON string into a Python dictionary using the json.loads() method −

import json

# JSON string
json_string = '{"name": "John", "age": 30, "is_student": false, "courses": ["Math", "Science"], "address": {"city": "New York", "state": "NY"}}'

# Deserialize JSON string to Python object
python_obj = json.loads(json_string)

print(python_obj)

以下是上面代码的输出: -

Following is the output of the above code −

{'name': 'John', 'age': 30, 'is_student': False, 'courses': ['Math', 'Science'], 'address': {'city': 'New York', 'state': 'NY'}}

Example: Deserialize JSON from File

现在,要读取和反序列化文件中的 JSON 数据,我们使用 json.load() 方法:

Now, to read and deserialize JSON data from a file, we use the json.load() method −

import json

# Read and deserialize from file
with open("data.json", "r") as f:
   python_obj = json.load(f)

print(python_obj)

上述代码的输出如下:

Output of the above code is as follows −

{'name': 'John', 'age': 30, 'is_student': False, 'courses': ['Math', 'Science'], 'address': {'city': 'New York', 'state': 'NY'}}

Advanced JSON Handling

如果你的 JSON 数据包含需要特殊处理的对象(例如自定义类),则可以定义自定义反序列化函数。使用 json.loads()json.load() 方法的 object_hook 参数来指定将在每个解码的 JSON 对象的结果中调用的函数。

If your JSON data includes objects that need special handling (e.g., custom classes), you can define custom deserialization functions. Use the object_hook parameter of json.loads() or json.load() method to specify a function that will be called with the result of every JSON object decoded.

Example

在下面的示例中,我们演示了自定义对象序列化的用法:

In the example below, we are demonstrating the usage of custom object serialization −

import json
from datetime import datetime

# Custom deserialization function
def custom_deserializer(dct):
   if 'joined' in dct:
      dct['joined'] = datetime.fromisoformat(dct['joined'])
   return dct

# JSON string with datetime
json_string = '{"name": "John", "joined": "2021-05-17T10:15:00"}'

# Deserialize with custom function
python_obj = json.loads(json_string, object_hook=custom_deserializer)

print(python_obj)

我们得到了如下输出 −

We get the output as shown below −

{'name': 'John', 'joined': datetime.datetime(2021, 5, 17, 10, 15)}

JSONEncoder Class

Python 中的 JSONEncoder 类用于将 Python 数据结构编码为 JSON 格式。每个 Python 数据类型都转换为其相应的 JSON 类型,如下表所示:

The JSONEncoder class in Python is used to encode Python data structures into JSON format. Each Python data type is converted into its corresponding JSON type, as shown in the following table −

JSONEncoder 类使用 JSONEncoder() 构造函数实例化。此类中定义了以下重要方法:

The JSONEncoder class is instantiated using the JSONEncoder() constructor. The following important methods are defined in this class −

  1. encode(obj) − Serializes a Python object into a JSON formatted string.

  2. iterencode(obj) − Encodes the object and returns an iterator that yields the encoded form of each item in the object.

  3. indent − Determines the indent level of the encoded string.

  4. sort_keys − If True, the keys appear in sorted order.

  5. check_circular − If True, checks for circular references in container-type objects.

Example

在以下示例中,我们对 Python 列表对象进行编码。我们使用 iterencode() 方法来显示编码字符串的每一部分:

In the following example, we are encoding Python list object. We use the iterencode() method to display each part of the encoded string −

import json

data = ['Rakesh', {'marks': (50, 60, 70)}]
e = json.JSONEncoder()

# Using iterencode() method
for obj in e.iterencode(data):
   print(obj)

它将生成如下输出:

It will produce the following output −

["Rakesh"
,
{
"marks"
:
[50
, 60
, 70
]
}
]

JSONDecoder class

JSONDecoder 类用于将 JSON 字符串解码回 Python 数据结构。此类中的主要方法是 decode()

The JSONDecoder class is used to decode a JSON string back into a Python data structure. The main method in this class is decode().

Example

在此示例中,“JSONEncoder”用于将 Python 列表编码为 JSON 字符串,“JSONDecoder”用于将 JSON 字符串解码回 Python 列表:

In this example, the "JSONEncoder" is used to encode a Python list into a JSON string, and the "JSONDecoder" is then used to decode the JSON string back into a Python list −

import json

data = ['Rakesh', {'marks': (50, 60, 70)}]
e = json.JSONEncoder()
s = e.encode(data)
d = json.JSONDecoder()
obj = d.decode(s)
print(obj, type(obj))

获得的结果如下所示 −

The result obtained is as shown below −

['Rakesh', {'marks': [50, 60, 70]}] <class 'list'>