Ruby JSON 编解码
介绍 Ruby 标准库 json 模块的环境准备、使用 JSON.parse 解析本地 JSON 文件为嵌套哈希与数组、JSON.generate/pretty_generate 序列化以及 symbolize_names 与解析错误处理。
学完这一章,你能够
- 介绍 Ruby 标准库 json 模块的环境准备、使用 JSON.parse 解析本地 JSON 文件为嵌套哈希与数组、JSON.generate/pretty_generate 序列化以及 symbolize_names 与解析错误处理。
JSON 模块环境配置
JSON(JavaScript Object Notation)是现代 Web API 与配置文件最通用的轻量数据交换格式。自 Ruby 1.9 起 `json` 模块已直接内置为 Ruby 标准库默认组件(default gem),无需额外手动安装即可直接 `require 'json'`(也不再需要旧版的 `require 'rubygems'`);仅在非常古老的 Ruby 版本或需要单独升级 C 扩展版本时,才需执行 `gem install json`。
使用 Ruby 解析与生成 JSON 数据
解析本地 `input.json` 文件非常简洁:引入 `json` 和用于美观打印的 `pp` 后,先调用 `json = File.read('input.json')` 读取 UTF-8 字符串,再调用 `obj = JSON.parse(json)` 即可将 JSON 对象映射为 Ruby `Hash`、JSON 数组映射为 Ruby `Array`(例如 `"India"`、`"Srilanka"`、`"England"` 对应的球员列表均转为字符串数组,`President` 与 `CEO` 转为键值对,通过 `pp obj` 直观输出)。反向将 Ruby 哈希或数组编码为 JSON 字符串时,可使用 `JSON.generate(obj)`(紧凑单行)或 `JSON.pretty_generate(obj)`(带缩进美化);若需直接获得符号键哈希可传入 `JSON.parse(json, symbolize_names: true)`,遇到语法非法的 JSON(如尾随逗号)则会抛出 `JSON::ParserError`。
离线校验 Ruby JSON.parse 解析、generate/pretty_generate 序列化与异常捕获
"""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()
- 3 个确定性用例全部通过,验证 input.json 嵌套键值解析、紧凑与美化往返编码以及非法 JSON 尾逗号报错。
所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
当前源码 SHA256:cac5d80e8e268f38ccbcc511eea77f6a9d1c80447130fda4996481e3505f46e1
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
ZIP SHA256:70fb0e305c4ed82763a97898d23eb149b08e307b05b1376ca71aab1dd48c3013
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Ruby 中调用 `JSON.parse(str)` 时,默认解析出的哈希键是 `String` 还是 `Symbol`?如何直接转换成 `Symbol` 键?
展开参考解答
默认解析出的哈希键是 `String` 类型;传入关键字参数 `JSON.parse(str, symbolize_names: true)` 即可直接生成 `Symbol` 键哈希。