示例工程 16-stdlib-tour
16-stdlib-tour/03-json-encode-decode/json_encode_decode.py
"""演示 json 的中文输出、自定义 default 与解码错误定位。"""
from __future__ import annotations
import json
from typing import Any
def main() -> None:
data: dict[str, Any] = {"name": "张三", "tags": ["a", "b"]}
print(f"ascii: {json.dumps(data)}")
pretty = json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True)
print("pretty:")
print(pretty)
print(f"roundtrip: {json.loads(pretty) == data}")
print(f"set default: {json.dumps({'s': {1, 2}}, default=sorted)}")
try:
json.loads('{"a": }')
except json.JSONDecodeError as exc:
print(f"decode error: line={exc.lineno} col={exc.colno} msg={exc.msg}")
if __name__ == "__main__":
main()