文章目录
目录
- JSON 是什么
- Python 自带神器:json模块
- JSON → Python(反序列化)
- Python → JSON(序列化)
- 优雅打印 JSON
- 从文件读取 JSON
- 把 JSON 写进文件
- JSON ↔ Python 类型对照表
- 异常处理
- 实战:抓取在线 API 数据
- 今日总结
JSON(JavaScript Object Notation)是一种轻量级数据格式,长得像 Python 的字典和列表:
{
"name": "Alice",
"age": 30,
"skills": ["Python", "Data Science"]
}
import json
用 json.loads() 把 JSON 字符串变成字典:
import json
json_str = '{"name": "Alice", "age": 30, "skills": ["Python", "Data Science"]}'
data = json.loads(json_str)
print(data["name"]) # Alice
print(type(data)) # <class 'dict'>
用 json.dumps() 把 Python 对象变 JSON 字符串:
person = {
"name": "Bob",
"age": 25,
"skills": ["JavaScript", "React"]
}
json_data = json.dumps(person)
print(json_data)
加 indent 一键格式化:
print(json.dumps(person, indent=2))
with open('data.json', 'r') as file:
data = json.load(file)
print(data["name"])
with open('output.json', 'w') as file:
json.dump(person, file, indent=4)
| JSON | Python |
|---|---|
| Object | dict |
| Array | list |
| String | str |
| Number | int/float |
| true/false | True/False |
| null | None |
解析失败时用 try-except 捕获:
try:
data = json.loads('{"name": "Alice", "age": }') # 非法 JSON
except json.JSONDecodeError as e:
print("解析出错:", e)
import requests
import json
response = requests.get("https://jsonplaceholder.typicode.com/users")
users = response.json()
for user in users:
print(user['name'], '-', user['email'])
| 任务 | 函数 |
|---|---|
| JSON → Python | json.loads() |
| Python → JSON | json.dumps() |
| 读文件 | json.load() |
| 写文件 | json.dump() |
到此这篇关于Python中JSON数据处理的完整指南的文章就介绍到这了,更多相关Python JSON数据处理内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- 在python中使用Json提取数据的详细过程
- Python进行JSON和Excel文件转换处理指南
- python读取文本文件内容转换为json格式的方法示例
- Python进行JSON数据处理的全攻略
- Python内置json实现数据本地持久化详解
- Python解析JSON数据的示例代码
- python之json格式解析与转换方式