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 数据。

相关推荐
databook21 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室1 天前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三1 天前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python