Python JSON基本操作

1. 什么是 JSON?

JSON(JavaScript Object Notation)一种轻量级的数据交换格式,广泛用于网络通信和数据存储。Python 标准库自带了 json 模块,可用于处理 JSON 数据。


2. Python JSON 常用操作

2.1 导入 JSON 模块

Python

import json

2.2 字典(dict)转 JSON 字符串

基本操作

Python

data = {'name': 'Tom', 'age': 20, 'city': 'Shanghai'}
json_str = json.dumps(data)
print(json_str)  # {"name": "Tom", "age": 20, "city": "Shanghai"}
添加中文支持

Python

# 确保中文字符不被转义
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)  # {"name": "Tom", "age": 20, "city": "Shanghai"}
格式化输出

Python

json_str = json.dumps(data, indent=4, ensure_ascii=False)
print(json_str)

2.3 JSON 字符串转字典

Python

json_str = '{"name": "Tom", "age": 20, "city": "Shanghai"}'
data = json.loads(json_str)
print(data)  # {'name': 'Tom', 'age': 20, 'city': 'Shanghai'}

2.4 Python 对象写入 JSON 文件

Python

data = {'name': 'Tom', 'age': 20}
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

2.5 读取 JSON 文件为 Python 对象

Python

with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
print(data)

3. JSON 列表操作

3.1 列表转 JSON

Python

lst = [1, 2, 3, {'a': 10, 'b': 20}]
json_str = json.dumps(lst)
print(json_str)  # [1, 2, 3, {"a": 10, "b": 20}]

3.2 JSON 列表字符串转 Python 列表

Python

json_str = '[1, 2, 3, {"a": 10, "b": 20}]'
lst = json.loads(json_str)
print(lst)

4. 其它进阶用法

4.1 对象编码自定义(复杂类型)

默认情况下,json.dumps() 不能直接序列化自定义对象。

Python

class User:
    def __init__(self, name, score):
        self.name = name
        self.score = score

user = User('Tom', 90)
# json.dumps(user)  # TypeError

# 方法1:添加 __dict__
json_str = json.dumps(user.__dict__)
print(json_str)  # {"name": "Tom", "score": 90}

# 方法2:自定义转换方法
def user2dict(obj):
    return {'name': obj.name, 'score': obj.score}

json_str = json.dumps(user, default=user2dict)
print(json_str)  # {"name": "Tom", "score": 90}

4.2 读写含多行(多条 JSON)

一行一条 JSON

Python

data_list = [{'id': 1}, {'id': 2}]
with open('multi.json', 'w', encoding='utf-8') as f:
    for item in data_list:
        f.write(json.dumps(item) + '\n')

# 读取
with open('multi.json', 'r', encoding='utf-8') as f:
    for line in f:
        print(json.loads(line.strip()))

5. 常见异常与解决

5.1 JSONDecodeError

  • 字符串格式必须严格遵循 JSON 规范(用双引号,不能有单引号)。
  • 文件内容不能为空。

5.2 指定字符串编码

  • 读写文件时建议加 encoding='utf-8',防止乱码。

6. JSON与文件内容示例

-data.json-

JSON

{
  "name": "Tom",
  "age": 20
}

7. 完整示例代码(读、写、格式化)

Python

import json

data = {
    "user": "Alice",
    "active": True,
    "scores": [10, 20, 30]
}

# 写入文件
with open('example.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

# 读取文件
with open('example.json', 'r', encoding='utf-8') as f:
    obj = json.load(f)

print(obj)

8. 相关速查表

操作说明方法
序列化为字符串json.dumps()
反序列化对象json.loads()
写入文件json.dump()
文件中读入对象json.load()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值