示例工程 16-stdlib-tour

16-stdlib-tour/03-json-encode-decode/README.md

markdown · 0.7 KB

# 03 · json-encode-decode
 
**演示**:`ensure_ascii=False` 输出可读中文、`default=` 处理 set、`JSONDecodeError` 的 `lineno`/`colno` 定位。
**运行**:
 
```sh
uv run python examples/16-stdlib-tour/03-json-encode-decode/json_encode_decode.py
```
 
**预期输出**(3.12.9):
 
```text
ascii: {"name": "\u5f20\u4e09", "tags": ["a", "b"]}
pretty:
{
  "name": "张三",
  "tags": [
    "a",
    "b"
  ]
}
roundtrip: True
set default: {"s": [1, 2]}
decode error: line=1 col=7 msg=Expecting value
```
 
**依赖**:仅标准库。
**注意**:`json.dumps` 的 `ensure_ascii` 默认是 `True`,中文会被转成 `\uXXXX`;写文件时同时指定 `encoding="utf-8"`,否则可能受平台默认编码影响。