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

相关推荐
小张是铁粉4 分钟前
docker学习二天之镜像操作与容器操作
学习·docker·容器
小张是铁粉29 分钟前
oracle的内存架构学习
数据库·学习·oracle·架构
HERR_QQ39 分钟前
【unify】unify的微信小程序开发学习 (to be continued)
学习·微信小程序·小程序
HuashuiMu花水木41 分钟前
Matplotlib笔记4----------图像处理
图像处理·笔记·matplotlib
3gying43 分钟前
chromedriver
python
DES 仿真实践家2 小时前
【Day 11-N22】Python类(3)——Python的继承性、多继承、方法重写
开发语言·笔记·python
云泽野6 小时前
【Java|集合类】list遍历的6种方式
java·python·list
技术小赵7 小时前
优化Facebook广告投放的五大关键策略
经验分享
IMPYLH8 小时前
Python 的内置函数 reversed
笔记·python
小赖同学啊10 小时前
物联网数据安全区块链服务
开发语言·python·区块链