"""Offline Ruby 3.x semantic verification lab for Chapter 44 (json)."""
import json
import tempfile
from pathlib import Path
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
SAMPLE_JSON = """{
"President": "Alan Isaac",
"CEO": "David Richardson",
"India": ["Sachin Tendulkar", "Virender Sehwag", "Gautam Gambhir"],
"Srilanka": ["Lasith Malinga", "Angelo Mathews", "Kumar Sangakkara"],
"England": ["Alastair Cook", "Jonathan Trott", "Kevin Pietersen"]
}"""
def case_json_parse_input_document():
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "input.json"
p.write_text(SAMPLE_JSON, encoding="utf-8")
obj = json.loads(p.read_text(encoding="utf-8"))
expected = {
"president": "Alan Isaac",
"ceo": "David Richardson",
"keys": ["President", "CEO", "India", "Srilanka", "England"],
"india_count": 3,
"first_england": "Alastair Cook",
}
actual = {
"president": obj["President"],
"ceo": obj["CEO"],
"keys": list(obj.keys()),
"india_count": len(obj["India"]),
"first_england": obj["England"][0],
}
return {
"name": "json_parse_input_document",
"summary": "在临时目录读取 input.json 并核验 JSON.parse 解析为嵌套哈希与数组结构",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_json_generate_pretty_and_types():
payload = {
"lang": "Ruby",
"version": 3.3,
"active": True,
"deprecated": None,
"tags": ["json", "stdlib"],
}
compact = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
pretty = json.dumps(payload, indent=2, ensure_ascii=False)
roundtrip = json.loads(compact)
expected = {
"compact_has_no_newlines": True,
"pretty_has_newlines": True,
"roundtrip_equal": True,
"null_encoded": '"deprecated":null',
}
actual = {
"compact_has_no_newlines": "\n" not in compact,
"pretty_has_newlines": "\n" in pretty,
"roundtrip_equal": roundtrip == payload,
"null_encoded": '"deprecated":null' if '"deprecated":null' in compact else "",
}
return {
"name": "json_generate_pretty_and_types",
"summary": "核验 JSON.generate 紧凑序列化、JSON.pretty_generate 缩进输出及 nil/Boolean/Array/Hash 类型往返",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_json_error_handling_and_symbolize():
bad_json = '{"President": "Alan Isaac",}'
caught_parse_error = False
try:
json.loads(bad_json)
except json.JSONDecodeError:
caught_parse_error = True
parsed = json.loads('{"host":"127.0.0.1","port":3000}')
symbolized = {f":{k}": v for k, v in parsed.items()}
expected = {
"trailing_comma_rejected": True,
"symbolized_keys": [":host", ":port"],
}
actual = {
"trailing_comma_rejected": caught_parse_error,
"symbolized_keys": list(symbolized.keys()),
}
return {
"name": "json_error_handling_and_symbolize",
"summary": "核验非法 JSON(尾随逗号)触发 JSON::ParserError 以及 symbolize_names 键转换语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_json_parse_input_document(),
case_json_generate_pretty_and_types(),
case_json_error_handling_and_symbolize(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
入口文件:projects/ruby-json-lab/explore-json.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-json.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联45章) · 含当前章节或实例 · mbskycom202612a2434.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2460.zip