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

相关推荐
DanCheng-studio5 分钟前
毕设 基于机器视觉的驾驶疲劳检测系统(源码+论文)
python·毕业设计·毕设
carpell7 分钟前
【语义分割专栏】3:Segnet实战篇(附上完整可运行的代码pytorch)
人工智能·python·深度学习·计算机视觉·语义分割
普宁彭于晏28 分钟前
元素水平垂直居中的方法
前端·css·笔记·css3
Tianyanxiao31 分钟前
华为×小鹏战略合作:破局智能驾驶深水区的商业逻辑深度解析
大数据·人工智能·经验分享·华为·金融·数据分析
一只小波波呀1 小时前
打卡第48天
python
whoarethenext1 小时前
C++ OpenCV 学习路线图
c++·opencv·学习
m0_637146931 小时前
计算机网络基础总结:TCP/IP 模型、TCP vs UDP、DNS 查询过程
笔记·tcp/ip·计算机网络
zstar-_1 小时前
一套个人知识储备库构建方案
python
恰薯条的屑海鸥1 小时前
零基础在实践中学习网络安全-皮卡丘靶场(第十四期-XXE模块)
网络·学习·安全·web安全·渗透测试
Lester_11011 小时前
嵌入式学习笔记 - freeRTOS vTaskPlaceOnEventList()函数解析
笔记·学习