蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

下载 JSON 编解码实验

PYTHON本地 Python 3 与 UTF-8 JSONpython3-json.py
python3-json.py109 行
"""蓝色天空网 mbsky.com · JSON 编解码与文件实验。"""
from decimal import Decimal
from enum import Enum, IntEnum
from io import BytesIO, StringIO
import json
import platform
from pathlib import Path
import sys
from tempfile import TemporaryDirectory

sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks


class Grade(IntEnum):
    READY = 2


class Ratio(float, Enum):
    HALF = 0.5


def reject_constant(token):
    raise ValueError(f"不接受 JSON 扩展数字 {token}")


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"重复成员 {key}")
        result[key] = value
    return result


def main():
    check = Checks()
    record = {"station": "北岸", "samples": 3, "reviewed": False, "note": None}
    document = json.dumps(record, ensure_ascii=False)
    check.eq("dumps returns JSON text", document,
             '{"station": "北岸", "samples": 3, "reviewed": false, "note": null}')
    check.raises("repr is Python notation", json.JSONDecodeError, lambda: json.loads(repr(record)))
    decoded = json.loads(document)
    check.eq("object decodes to dictionary", decoded, record)
    check.eq("decoded fields", (decoded["station"], decoded["samples"]), ("北岸", 3))
    check.eq("explicit null member is retained", ("note" in decoded, decoded["note"]), (True, None))
    check.eq("both sequence types encode as arrays", (json.dumps([3, 1]), json.dumps((3, 1))),
             ("[3, 1]", "[3, 1]"))
    check.eq("array decodes in order to list", json.loads("[3,1]"), [3, 1])
    check.eq("boolean and null encoding", [json.dumps(x) for x in (True, False, None)],
             ["true", "false", "null"])
    check.eq("true decodes to bool", json.loads("true"), True)
    check.eq("false decodes to bool", json.loads("false"), False)
    check.eq("null decodes to None", json.loads("null"), None)
    check.eq("ordinary numbers encode as numbers", [json.dumps(x) for x in (3, 0.5)], ["3", "0.5"])
    check.eq("numeric enums encode as numbers", [json.dumps(x) for x in (Grade.READY, Ratio.HALF)],
             ["2", "0.5"])
    check.eq("integer token decodes to int", json.loads("3"), 3)
    check.eq("fraction token decodes to float", json.loads("0.5"), 0.5)
    check.eq("exponent token decodes to float", json.loads("3e0"), 3.0)
    check.eq("default Unicode escaping", json.dumps("北岸"), '"\\u5317\\u5cb8"')
    check.eq("string escapes decode to Unicode", json.loads('"北岸\\n\\"A\\""'), '北岸\n"A"')
    check.eq("integer key becomes a string", json.loads(json.dumps({3: "站点"})), {"3": "站点"})
    check.raises("tuple key rejected by default", TypeError, lambda: json.dumps({(1, 2): "站点"}))
    check.eq("default duplicate member policy", json.loads('{"x":1,"x":2}'), {"x": 2})
    check.raises("hook rejects duplicate members", ValueError,
                 lambda: json.loads('{"x":1,"x":2}', object_pairs_hook=unique_object))
    check.eq("Decimal hook sees the original token", str(json.loads("0.100", parse_float=Decimal)), "0.100")
    check.eq("default allows extension tokens", json.dumps([float("nan"), float("inf")]),
             "[NaN, Infinity]")
    check.raises("strict encoding rejects nonfinite number", ValueError,
                 lambda: json.dumps(float("inf"), allow_nan=False))
    check.raises("strict decoding rejects extension token", ValueError,
                 lambda: json.loads("NaN", parse_constant=reject_constant))
    try:
        json.loads('{\n"x": }')
    except json.JSONDecodeError as exc:
        check.eq("decode error position", (exc.lineno, exc.colno, exc.pos), (2, 6, 7))
    else:
        raise AssertionError("expected malformed JSON to fail")

    with TemporaryDirectory(prefix="mbsky-json-") as temp:
        path = Path(temp) / "observations.json"
        with path.open("w", encoding="utf-8", newline="\n") as stream:
            result = json.dump(record, stream, ensure_ascii=False, indent=2)
            stream.write("\n")
        check.eq("dump returns None", result, None)
        fixture = Path(__file__).with_name("json-observation-lab.json")
        check.eq("written UTF-8 matches the owned sample", path.read_bytes(), fixture.read_bytes())
        with path.open("r", encoding="utf-8") as stream:
            check.eq("load reopens written JSON", json.load(stream), record)
        check.eq("loads accepts UTF-8 bytes", json.loads(path.read_bytes()), record)
    with BytesIO() as binary:
        check.raises("dump requires a text writer", TypeError, lambda: json.dump(record, binary))
    with StringIO() as stream:
        json.dump(record, stream)
        json.dump(record, stream)
        stream.seek(0)
        check.raises("concatenated documents are invalid", json.JSONDecodeError, lambda: json.load(stream))

    check.finish("python3-json", python=platform.python_version(),
                 implementation=platform.python_implementation(), platform=platform.platform(),
                 input=record, operations="UTF-8 temporary file, in-memory strings and streams",
                 network=False)


if __name__ == "__main__":
    main()
本例需在 本地 Python 3 与 UTF-8 JSON 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 3 与 UTF-8 JSON

入口文件:projects/python-lab/python3-json.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python3-json.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 3 与 UTF-8 JSON。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习