苦练Python第36天:Python的JSON数据处理指南

208 阅读1分钟

前言

大家好,我是倔强青铜三。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!

欢迎来到 Python 百日冲刺第 36 天

今天,我们把目光投向现实世界最通用的数据语言——JSON。API、配置、数据库,处处都有它的身影。五分钟掌握 Python 内置 json 模块,读写解析一气呵成!


📦 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 类型对照表

JSONPython
Objectdict
Arraylist
Stringstr
Numberint/float
true/falseTrue/False
nullNone

🧨 异常处理

解析失败时用 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 → Pythonjson.loads()
Python → JSONjson.dumps()
读文件json.load()
写文件json.dump()

最后感谢阅读!欢迎关注我,微信公众号倔强青铜三。欢迎点赞收藏关注,一键三连!!!