json 是什么
json(javascript object notation)是一种轻量级数据格式,长得像 python 的字典和列表:
{ "name": "alice", "age": 30, "skills": ["python", "data science"] }
python 自带神器:json模块
import json
json → python(反序列化)
用 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'>
python → json(序列化)
用 json.dumps()
把 python 对象变 json 字符串:
person = { "name": "bob", "age": 25, "skills": ["javascript", "react"] } json_data = json.dumps(person) print(json_data)
优雅打印 json
加 indent
一键格式化:
print(json.dumps(person, indent=2))
从文件读取 json
with open('data.json', 'r') as file: data = json.load(file) print(data["name"])
把 json 写进文件
with open('output.json', 'w') as file: json.dump(person, file, indent=4)
json ↔ python 类型对照表
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)
实战:抓取在线 api 数据
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数据处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论