将 Python 的宝物 (Dict/List) 转化为 JSON 字符串。
import json
data = {
"name": "路人Py",
"level": 99,
"has_gf": False
}
# 序列化 (Serialize):变成字符串
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)
# 结果: '{"name": "路人Py", "level": 99, "has_gf": false}'
注意:Python 的 False 变成了 JSON 的 false (小写)。
将 JSON 字符串变回 Python 的宝物。
# 收到一张符箓
msg = '{"cmd": "attack", "damage": 100}'
# 反序列化 (Deserialize)
obj = json.loads(msg)
print(obj["cmd"]) # attack
直接对着玉简 (File) 操作。
# 存入玉简
with open("data.json", "w") as f:
json.dump(data, f)
# 读取玉简
with open("data.json", "r") as f:
data = json.load(f)
任务:将字典 {"a": 1, "b": 2} 转化为 JSON 字符串并打印。