Python JSON怎么处理和操作?

文章导读
Previous Quiz Next Python 中的 JSON Python 中的 JSON 是一种流行的数据格式,用于系统之间的数据交换。json 模块提供了处理 JSON 数据的方法,允许你将 Python 对象序列化为 JSON 字符串,并将 JSON 字符串反序
📋 目录
  1. A Python 中的 JSON
  2. B JSON 序列化
  3. C JSON 反序列化
  4. D 高级 JSON 处理
  5. E JSONEncoder 类
  6. F JSONDecoder 类
  7. G Python JSON 模块方法
  8. H 核心函数
  9. I JSON 编码器方法
  10. J JSON 解码器方法
A A

Python - JSON



Previous
Quiz
Next

Python 中的 JSON

Python 中的 JSON 是一种流行的数据格式,用于系统之间的数据交换。json 模块提供了处理 JSON 数据的方法,允许你将 Python 对象序列化为 JSON 字符串,并将 JSON 字符串反序列化为 Python 对象。

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人类阅读和编写,同时也易于机器解析和生成。它主要以文本形式用于服务器和 Web 应用程序之间传输数据。

JSON 序列化

JSON 序列化是将 Python 对象转换为 JSON 格式的过程。这对于保存可以轻松传输或存储的数据格式很有用,并且可以稍后重建为原始形式。

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

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

  • dict
  • list
  • tuple
  • str
  • int
  • float
  • bool
  • None

示例

以下是一个将 Python 字典序列化为 JSON 字符串的基本示例 −

import json

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

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

它将产生以下输出 −

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

JSON 反序列化

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

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

示例:将 JSON 字符串反序列化为 Python 对象

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

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)

以上代码的输出如下 −

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

示例:从文件反序列化 JSON

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

import json

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

print(python_obj)

以上代码的输出如下 −

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

高级 JSON 处理

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

示例

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

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)

我们得到的输出如下所示 −

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

JSONEncoder 类

Python 中的 JSONEncoder 类用于将 Python 数据结构编码为 JSON 格式。每种 Python 数据类型都会转换为对应的 JSON 类型,如下表所示 −

Python JSON
Dict object
list, tuple array
Str string
int, float, int- & float-derived Enums number
True true
False false
None null

JSONEncoder 类通过 JSONEncoder() 构造函数实例化。该类中定义了以下重要方法 −

  • encode(obj) − 将 Python 对象序列化为 JSON 格式的字符串。

  • iterencode(obj) − 编码对象并返回一个迭代器,该迭代器产生对象中每个项的编码形式。

  • indent − 确定编码字符串的缩进级别。

  • sort_keys − 如果为 True,键将按排序顺序出现。

  • check_circular − 如果为 True,则检查容器类型对象中的循环引用。

示例

在以下示例中,我们编码 Python list 对象。我们使用 iterencode() 方法来显示编码字符串的每个部分 −

import json

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

# 使用 iterencode() 方法 
for obj in e.iterencode(data):
   print(obj)

将产生以下输出 −

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

JSONDecoder 类

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

示例

在本示例中,"JSONEncoder" 用于将 Python list 编码为 JSON 字符串,然后 "JSONDecoder" 用于将 JSON 字符串解码回 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))

得到的结果如下所示 −

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

Python JSON 模块方法

Python 中的 json 模块提供了处理 JSON(JavaScript Object Notation)的方法。它允许您将 Python 对象序列化和反序列化为 JSON 格式,这是一种常用的数据交换格式。

核心函数

json 模块中的核心函数允许您序列化和反序列化 JSON 数据。

序号 函数 & 描述
1 json.dump()

序列化 Python 对象并将其写入文件式对象。

2 json.dumps()

序列化 Python 对象并将其返回为 JSON 格式的字符串。

3 json.load()

将 JSON 格式的流反序列化为 Python 对象。

4 json.loads()

将 JSON 格式的字符串反序列化为 Python 对象。

JSON 编码器方法

JSON 编码器方法处理 Python 对象到 JSON 格式的转换。

序号 函数 & 描述
1 json.JSONEncoder

用于将 Python 对象转换为 JSON 格式的编码器类。

2 json.JSONEncoder.encode()

将 Python 对象编码为 JSON 格式的字符串。

3 json.JSONEncoder.iterencode()

以迭代器风格将 Python 对象编码为 JSON 格式。

4 json.JSONEncoder.default()

重写方法,用于处理默认情况下不可序列化的对象。

JSON 解码器方法

JSON 解码器方法处理 JSON 数据到 Python 对象的转换。

序号 函数 & 描述
1 json.JSONDecoder

用于将 JSON 数据转换为 Python 对象的解码器类。

2 json.JSONDecoder.decode()

将 JSON 字符串反序列化为 Python 对象。

3 json.JSONDecoder.raw_decode()

反序列化 JSON 字符串并提供错误处理用的额外信息。

实用函数

实用函数提供了在 Python 中处理 JSON 数据的简单方法。

序号 函数 & 描述
1 json.tool

提供命令行工具,用于格式化 JSON 数据以提高可读性。

JSONEncoder 中的 Dunder(Magic)方法

这些是 json 模块中 JSONEncoder class 的特殊方法,用于实现 JSON 序列化的自定义行为。

序号 方法 & 描述
1 json.JSONEncoder.__init__

使用自定义设置初始化编码器。

2 json.JSONEncoder.__repr__

返回编码器对象的字符串表示。

3 json.JSONEncoder.__str__

返回编码器对象的字符串版本。

JSONDecoder 中的 Dunder(Magic)方法

这些是 JSONDecoder class 的特殊方法,用于实现 JSON 反序列化的自定义行为。

序号 方法 & 描述
1 json.JSONDecoder.__init__

使用自定义设置初始化解码器。

2 json.JSONDecoder.__repr__

返回解码器对象的字符串表示。

3 json.JSONDecoder.__str__

返回解码器对象的字符串版本。

json.encoder 中的函数(内部工具函数)

这些函数在 json.encoder 模块中被内部使用,用于处理特定的编码任务。

序号 函数 & 描述
1 json.encoder.encode_basestring()

将字符串编码为 JSON 兼容格式。

2 json.encoder.encode_basestring_ascii()

将字符串编码为 JSON 兼容的 ASCII 格式。

json.decoder 中的函数(内部工具函数)

这些函数在 json.decoder 模块中被内部使用,用于处理特定的解码任务。

序号 函数 & 描述
1 json.decoder.scanstring()

扫描 JSON 格式的字符串。

2 json.decoder.JSONArray()

处理 JSON 数组解码。

json 模块中的属性

json 模块中提供各种配置设置和常量的属性。

序号 属性 & 描述
1 json.decoder

包含与解码器相关的函数和 class。

2 json.encoder

包含与编码器相关的函数和 class。

3 json.__all__

使用 import * 时导出的模块属性列表。

4 json.__version__

json 模块的版本号。

json.encoder 中的属性

json.encoder 模块中与编码功能相关的属性。

序号 属性 & 描述
1 json.encoder.FLOAT_REPR

控制序列化过程中浮点数的表示方式。

2 json.encoder._make_iterencode()

用于创建基于迭代器的编码器的内部工具函数。

json.decoder 中的属性

json.decoder 模块中与解码功能相关的属性。

序号 属性 & 描述
1 json.decoder.JSONDecoder

用于将 JSON 数据转换为 Python 对象的解码器 class。

2 json.decoder.JSONDecoder.object_hook

用于解析和转换 JSON 对象的函数。

3 json.decoder.JSONDecoder.parse_float

自定义 JSON 数据中浮点数解码的函数。

4 json.decoder.JSONDecoder.parse_int

自定义 JSON 数据中整数解码的函数。

5 json.decoder.JSONDecoder.parse_constant

处理 JSON 解码过程中 True、False 和 None 等常量值的函数。

6 json.decoder.JSONDecoder.object_pairs_hook

用于解析 JSON 对象并控制其键值对的函数。

JSON 中的属性(内部使用)

这些属性在 json 模块中用于内部使用。

序号 属性 & 描述
1 json._default_decoder

用于解码 JSON 数据的默认 JSON 解码器。

2 json._default_encoder

用于将 Python 对象编码为 JSON 的默认 JSON 编码器。