json序列化与反序列化

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于前后端数据传输。Python 的 json 模块提供了序列化(将 Python 对象转换为 JSON 格式)和反序列化(将 JSON 格式转换回 Python 对象)的功能。

JSON 序列化(Python 对象 → JSON 字符串)

使用 json.dumps() 或 json.dump() 方法:

  • json.dumps(obj):将 Python 对象转换为 JSON 字符串。
  • json.dump(obj, file):将 Python 对象写入文件。

示例 1:基本数据类型序列化 

import json

# Python 字典 → JSON 对象
data = {
    "name": "Alice",
    "age": 30,
    "is_student": False,
    "hobbies": ["reading", "coding"],
    "address": {
        "city": "Beijing",
        "zipcode": "100000"
    }
}

# 转换为 JSON 字符串
json_str = json.dumps(data, indent=2)  # indent 参数美化格式
print(json_str)

# 输出:
# {
#   "name": "Alice",
#   "age": 30,
#   "is_student": false,
#   "hobbies": ["reading", "coding"],
#   "address": {
#     "city": "Beijing",
#     "zipcode": "100000"
#   }
# }

示例 2:写入文件 

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)  # 直接写入文件

JSON 反序列化(JSON 字符串 → Python 对象)

使用 json.loads() 或 json.load() 方法:

  • json.loads(json_str):将 JSON 字符串解析为 Python 对象。
  • json.load(file):从文件读取并解析 JSON。

示例 3:解析 JSON 字符串 

json_str = '{"name": "Bob", "age": 25, "is_student": true}'
data = json.loads(json_str)
print(data)  # 输出:{'name': 'Bob', 'age': 25, 'is_student': True}
print(type(data))  # 输出:<class 'dict'>

示例 4:从文件读取 JSON 

with open("data.json", "r") as f:
    data = json.load(f)  # 从文件读取并解析
print(data)

JSON 与 Python 类型映射

JSON 类型Python 类型
objectdict
arraylist
stringstr
numberintfloat
trueTrue
falseFalse
nullNone

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值