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

相关推荐
这里有鱼汤14 分钟前
【花姐小课堂】新手也能秒懂!用「风险平价」打造扛造的投资组合
后端·python
databook14 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar15 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户83562907805115 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_15 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机1 天前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机1 天前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i1 天前
drf初步梳理
python·django