python库 - json

文章目录


json 是 Python 标准库中的一个模块,用于处理 JSON(JavaScript Object Notation)数据格式。JSON 是一种轻量级的数据交换格式,易于人类阅读和编写,同时也易于机器解析和生成。json 模块提供了将 Python 对象转换为 JSON 格式的字符串(序列化)以及将 JSON 格式的字符串转换为 Python 对象(反序列化)的功能。

主要功能

  1. 序列化(Encoding):将 Python 对象转换为 JSON 字符串。
  2. 反序列化(Decoding):将 JSON 字符串转换为 Python 对象。
  3. 文件操作:支持从文件中读取 JSON 数据或将 JSON 数据写入文件。
  4. 自定义序列化和反序列化:允许用户自定义对象的序列化和反序列化行为。

常用函数

1. json.dumps()

将 Python 对象转换为 JSON 格式的字符串。

python 复制代码
import json

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

json_string = json.dumps(data)
print(json_string)

输出:

json 复制代码
{"name": "Alice", "age": 30, "city": "New York"}
2. json.loads()

将 JSON 格式的字符串转换为 Python 对象。

python 复制代码
import json

json_string = '{"name": "Alice", "age": 30, "city": "New York"}'
data = json.loads(json_string)
print(data)

输出:

python 复制代码
{'name': 'Alice', 'age': 30, 'city': 'New York'}
3. json.dump()

将 Python 对象序列化为 JSON 格式并写入文件。

python 复制代码
import json

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

with open('data.json', 'w') as f:
    json.dump(data, f)
4. json.load()

从文件中读取 JSON 数据并转换为 Python 对象。

python 复制代码
import json

with open('data.json', 'r') as f:
    data = json.load(f)
print(data)

自定义序列化和反序列化

json 模块允许用户自定义对象的序列化和反序列化行为。可以通过定义 default 函数来实现自定义序列化,通过定义 object_hook 函数来实现自定义反序列化。

自定义序列化
python 复制代码
import json

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

def person_to_json(obj):
    if isinstance(obj, Person):
        return {'name': obj.name, 'age': obj.age}
    else:
        raise TypeError(f'Object of type {obj.__class__.__name__} is not JSON serializable')

person = Person("Alice", 30)
json_string = json.dumps(person, default=person_to_json)
print(json_string)
自定义反序列化
python 复制代码
import json

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

def json_to_person(dct):
    if 'name' in dct and 'age' in dct:
        return Person(dct['name'], dct['age'])
    return dct

json_string = '{"name": "Alice", "age": 30}'
person = json.loads(json_string, object_hook=json_to_person)
print(person.name, person.age)

json 模块是 Python 中处理 JSON 数据的标准库,提供了丰富的功能来序列化和反序列化 JSON 数据。无论是简单的字典和列表,还是自定义的对象,json 模块都能很好地支持。通过灵活使用 json 模块,可以在 Python 程序中处理 JSON 数据。

相关推荐
崇山峻岭之间几秒前
Matlab学习记录20
开发语言·学习·matlab
童话名剑1 分钟前
迁移学习示例 和 数据增强(吴恩达深度学习笔记)
笔记·深度学习·数据增强·迁移学习
逍遥德3 分钟前
JPA 操作对象图 (Object Graph) 详解
开发语言·python
deephub13 分钟前
DeepSeek 开年王炸:mHC 架构用流形约束重构 ResNet 残差连接
人工智能·python·深度学习·神经网络·残差链接
笔夏15 分钟前
【安卓学习之myt】adb常用命令
android·学习·adb
上班职业摸鱼人18 分钟前
MMDetection 框架完整教程(从入门到实战,代码可复现)
python
意趣新20 分钟前
OpenCV 中摄像头视频采集 + 实时显示 + 视频保存
python·opencv·计算机视觉
清水白石00822 分钟前
《Python 中 deque vs list:性能差异全解析与高效数据结构实战指南》
数据结构·python·list
智航GIS27 分钟前
7.2 Try Except语句
开发语言·python