A non-recursive, zero-copy JSON kernel: exact integers, verbatim round-trip, span-based in-place editing.
// 依赖:moonbitlang/core/encoding/utf8(仅用于把输出字节转成可打印的 String)
let doc = @core.Doc::parse_string("{\"a\": 1, \"b\": {\"x\":[true]}}")
println(doc.get_pointer("/b/x/0").unwrap().as_bool().unwrap()) // true
println(@utf8.decode_lossy(doc.set_pointer_string("/b", "{\"x\":[false]}")))
// {"a": 1, "b": {"x":[false]}} ← 注意 "a": 1, 中间的空格还在| 代价 | 后果 |
|---|---|
| 复制 | String/数字全部重新分配。1.6 MiB 的文档读完,堆上多出接近 1.6 MiB,中途还有大量小对象。 |
| 重排 | 输出是"重新生成"的,不是"原来那份"。缩进被统一、1.0 打印成 1、\/ 被规范成 /、空行消失(core/json 实测如此,见 §4 场景二)。所以任何"读进来改一个字段再存回去"的流程,都会让整个文件的 diff 变脏。 |
| 递归 | parse_value 调用 parse_array 调用 parse_value,深度 = 栈深度。所以读者必须在某个深度上设一道闸,并在闸门之外另备一条路。core/json 的做法是混合的:前 128 层递归(快),超出后把剩余文档交给 stack_safe_parse 的显式栈(稳)。这是对的设计,代价是两套代码路径,且深文档只能走慢的那条——见 §4 场景一的实测。 |
lane 0 kind lane 4 key_end
lane 1 start lane 5 first_child
lane 2 end lane 6 next_sibling
lane 3 key_start lane 7 child_countmoon add TIMI0821/jsonspinename = "TIMI0821/jsonspine"
version = "0.1.0"
preferred_target = "wasm-gc"
license = "Apache-2.0"| 组件 | 版本 |
|---|---|
| moon | 0.1.20261126 (ccd306a 2026-11-26) |
| moonc | v1.0.0-rc1+3c0520448 |
| 验证目标 | wasm-gc、js |
moon version --all # 确认你的版本native 目标需要本机 C 编译器(MSVC 或 GCC)。本仓库的 CI 与本地验证都跑 wasm-gc / js 两个后端,二者都能完整跑通全部测试。
// 10 万层嵌套数组
let depth = 100_000
let text = "[".repeat(depth) + "]".repeat(depth)
let doc = @core.Doc::parse_with(
@utf8.encode(text),
@core.Options::new(max_depth=depth + 1),
)
println(doc.max_depth()) // 100000
println(doc.to_bytes().length()) // 200000,逐字节原样回写| 嵌套深度 | jsonspine | core json | 说明 |
|---|---|---|---|
| 1 000 | 18 ns/B | 31 ns/B | 本项目每层少分配一个 Map/Vec |
| 5 000 | 37 ns/B | 38 ns/B | 基本持平 |
| 10 000 | 37 ns/B | 44 ns/B | |
| 100 000 | 35 ns/B | 103 ns/B | core 每层留一个堆帧且全程持有 |
moon run bench/deep --target wasm-gc -- 1000 core
moon run bench/deep --target wasm-gc -- 1000 spine
moon run bench/deep --target wasm-gc -- 100000 core
moon run bench/deep --target wasm-gc -- 100000 spinelet doc = @core.Doc::parse_string("12345678901234567890")
let n = doc.root()
println(n.as_int64()) // None:超出 Int64,明确拒绝而不是截断
println(n.as_double()) // Some(12345678901234567000):要近似就给近似,它明显不再等于原文
println(n.number_text().unwrap())// 12345678901234567890:原文一字不差| 输入 | core/json 输出 | jsonspine 输出 |
|---|---|---|
| 1.0 | 1 | 1.0 |
| "a\/b" | "a/b" | "a\/b" |
| 12345678901234567890 | 12345678901234567890 | 12345678901234567890 |
| 带缩进/空行的源文本 | 压缩、重排 | to_string() 同样压掉空白;to_bytes() 与 set_pointer() 保留 |
moon run cmd/main -- check '{"a":1,"b":2}' # verbatim=true
moon run cmd/main -- check '{"a": 1, "b": 2}' # verbatim=false(空白不属于节点)
moon run cmd/main -- check '1.0' # verbatim=true(数字拼写保留)
moon run cmd/main -- check '"a\/b"' # verbatim=true(转义选择保留)let src = "{\n \"name\": \"svc\",\n \"port\": 8080,\n \"debug\": false\n}"
let doc = @core.Doc::parse_string(src)
let out = doc.set_pointer_string("/debug", "true")
println(@utf8.decode_lossy(out))
// {
// "name": "svc",
// "port": 8080,
// "debug": true
// }let doc = @core.Doc::parse_string(
"{\"users\":[{\"name\":\"ada\"},{\"name\":\"lin\"}]}",
)
println(doc.get_pointer("/users/1/name").unwrap().as_string().unwrap()) // lin
println(doc.has_pointer("/users/9")) // false| 函数 | 说明 |
|---|---|
| Doc::parse(src : Bytes) -> Doc raise ParseError | 用默认选项解析 |
| Doc::parse_string(text : String) -> Doc raise ParseError | 同上,收 String |
| Doc::parse_with(src : Bytes, opts : Options) -> Doc raise ParseError | 指定上限与开关 |
| 函数 | 说明 |
|---|---|
| Doc::root() -> Value | 根节点 |
| Doc::node_count() -> Int32 | 节点总数(含容器与叶子) |
| Doc::max_depth() -> Int32 | 最大嵌套深度(标量为 0) |
| Doc::bytes() -> Int32 / to_bytes() -> Bytes | 源字节长度 / 源字节(绝对原文,永远一字不差) |
| Doc::to_string() -> String | 从节点重建,紧凑输出。节点内容是其原文 span(数字拼写、转义、键顺序原样),但空白不属于节点、会被压掉 |
| Doc::to_pretty_string(indent? : Int32) -> String | 美化输出,默认 2 空格 |
| Doc::is_verbatim() -> Bool | 本次 to_string() 是否恰好等于原文(等价于“源里没有任何节点之外的字节”) |
| 函数 | 说明 |
|---|---|
| kind() / is_object() / is_array() / is_string() / is_number() / is_null() | 类型判断 |
| as_bool() -> Bool? | |
| raw() -> BytesView | 原文视图,零拷贝 |
| span() -> Span | [start, end) 字节区间 |
| string_bytes() -> BytesView? | 字符串内容视图(不含引号,未反转义) |
| as_string() -> String? | 反转义后的字符串(此时才分配) |
| number_text() -> String? / as_double() -> Double? / as_int64() -> Int64? / as_int() -> Int32? | 数字的四种读法 |
| len() -> Int32 / at(Int32) -> Value? / key() -> String? / get(String) -> Value? | 容器访问 |
| key_bytes() / key_span() / children() -> Array[Value] | 键的视图与子节点遍历 |
| 函数 | 说明 |
|---|---|
| pointer_segments(pointer) -> Array[String] raise ParseError | 单独的分段器 |
| Doc::get_pointer(pointer) -> Value? raise ParseError | 查询,不存在返回 None |
| Doc::has_pointer(pointer) -> Bool raise ParseError | 是否存在 |
| Doc::set_pointer(pointer, value : Bytes) -> Bytes raise ParseError | 替换,返回新文档字节 |
| Doc::set_pointer_string(pointer, value : String) -> Bytes raise ParseError | 同上,收 String |
| Doc::remove_pointer(pointer) -> Bytes raise ParseError | 删除成员/元素,连同分隔逗号 |
| 变体 | 显示文案 |
|---|---|
| UnexpectedEnd | unexpected end of input |
| ExpectedValue | expected a value |
| ExpectedKey | expected a string key |
| ExpectedColon | expected ':' after a key |
| ExpectedCommaOrEnd | expected ',' or the end of the container |
| TrailingContent | trailing content after the document |
| InvalidNumber | malformed number |
| InvalidEscape | unknown escape sequence |
| InvalidUnicodeEscape | malformed \u escape |
| ControlByteInString | unescaped control byte in a string |
| UnterminatedString | unterminated string |
| InvalidUtf8 | invalid UTF-8 |
| DuplicateKey | duplicate object key |
| DepthExceeded | nesting deeper than the configured limit |
| InvalidPointer | not a JSON Pointer |
let e = try { @core.Doc::parse_string("{\"a\":1,}") |> ignore; "" } catch { e => e.message() }
println(e) // 1:8: expected a string key (byte 7)moon run cmd/main -- check '{"a":[1,2],"b":{"c":true}}'
# ok: 6 nodes, depth 2, 26 bytes, verbatim=true
moon run cmd/main -- stats '{"a":[1,2],"b":{"c":true}}'
# kind: object
# members: 2
# nodes: 6, depth: 2
# a: array
# b: object
moon run cmd/main -- get '{"a":[1,2]}' /a/1
# number: 2
moon run cmd/main -- set '{"a": 1, "b": {"x":[true]}}' /b '{"x":[false]}'
# {"a": 1, "b": {"x":[false]}}
moon run cmd/main -- pretty '{"a":1,"b":[true,null]}'
# {
# "a": 1,
# "b": [
# true,
# null
# ]
# }Git Bash / MSYS 会把 /a/1 这类参数当路径转换掉。在这些 shell 里先 export MSYS_NO_PATHCONV=1,或改用 cmd/PowerShell。
moon run examples/tour[1] a document nobody wants to read recursively
depth: 20000
nodes: 20000
bytes back: 40000
under the default limit (512): refused: 1:513: nesting deeper than the configured limit (byte 512)
[2] a number that does not fit in anything convenient
kind: number
as_int64: None
as_double: 12345678901234567000
number_text: 12345678901234567890
raw bytes: 12345678901234567890
[3] changing one value without touching the rest
{
"name": "svc",
"port": 8080,
"debug": true
}
bytes before: 55
bytes after: 54
[4] reaching into a document without materialising it
/users/1/name -> string "lin"
/n -> number 2
/users/9 -> (nothing)
/a~1b -> 1corpus: 1.6178 MiB, 12000 records
--- parse ---
jsonspine 15.4 ms/run 105.1 MiB/s
core json 26.8 ms/run 60.4 MiB/s
--- write ---
jsonspine 10.8 ms/run 149.8 MiB/s
core json 15.4 ms/run 105.1 MiB/s
--- lookup ---
jsonspine: 55 µs for 5 pointer lookups (≈11 µs/次)
--- deep nesting ---
jsonspine: 8 ms for 100 000 nested arraysmoon run bench/main --target wasm-gc # 吞吐、查询、深嵌套
moon run bench/deep --target wasm-gc -- 100000 core # 深嵌套:core/json
moon run bench/deep --target wasm-gc -- 100000 spine # 深嵌套:jsonspine| 能力 | core/json | 典型第三方 JSON 包 | jsonspine |
|---|---|---|---|
| 物化 Json 枚举 | ✅ | ✅ | ❌(设计如此) |
| 零拷贝取值(BytesView 视图) | ❌ | ❌ | ✅ |
| 非递归解析 | ⚠️ 混合:128 层以内递归,超出切 stack_safe_parse 显式栈 | ❌(纯递归) | ✅ 单一路径,无预算 |
| 逐字节 verbatim 往返 | ❌ | ❌ | ✅ |
| 精确整数(超 Int64 明确返回 None) | 部分 | 部分 | ✅(不截断、不静默转 double) |
| 原位编辑(最小字节 diff) | ❌ | ❌ | ✅ |
| JSON Pointer (RFC 6901) | ❌ | 少见 | ✅ |
| Json 枚举的便捷模式匹配 | ✅ | ✅ | ❌(用 kind() + 访问器) |
moon test --target wasm-gc
moon test --target js| 文件 | 覆盖 |
|---|---|
| core/conformance_test.mbt | 89 份一致性文档:42 份必须接受、47 份必须拒绝;另有两组交叉验证(每份接受文档读-写-读一致;每份接受文档与 @json.parse 的值相等) |
| core/parse_test.mbt | 标量、空白、嵌套、空容器、数字原样保留、超 double 整数、转义解码、BOM 拒绝、单引号拒绝、重复键、节点数/深度、逐字节往返 |
| core/error_test.mbt | 15 种 ErrorKind 逐一断言到文案(不是只断言“报错了”);行号列号定位;非法 UTF-8(Bytes::from_array 构造);01 必须报 malformed number 而不是 trailing content |
| core/encode_test.mbt | 紧凑/美化输出、数字拼写保留、读-写-读一致、is_verbatim |
| core/pointer_test.mbt | 分段、空 token、~0/~1 转义、不存在的路径 |
| core/patch_test.mbt | 原位编辑保留其它字节;数组元素、容器、根替换;非法替换被拒;不存在路径被拒;删除首/末/唯一成员;源文档不被修改 |
| core/depth_test.mbt | 10 万层数组与对象;默认上限 512 生效 |
# 1. 工具链
moon version --all
# 2. 静态检查(零告警)
moon check --deny-warn
# 3. 构建
moon build --release
# 4. 测试(两个后端)
moon test --target wasm-gc
moon test --target js
# 5. 格式与接口快照
moon fmt --check
moon info
# 6. CLI
moon run cmd/main -- check '{"a":[1,2],"b":{"c":true}}'
# 7. 基准
moon run bench/main --target wasm-gc
# 8. 深嵌套对照(两种读取器的每字节成本)
moon run bench/deep --target wasm-gccore/ 库本体(零依赖,除 core 标准库)
types.mbt ValueKind / ErrorKind / ParseError / Options / Span
scan.mbt 字节级扫描:字符串、数字、UTF-8 区间校验
parse.mbt 节点竞技场 + 三态状态机(非递归)
access.mbt Value 访问器、反转义、精确数字读取
encode.mbt 迭代式编码器(verbatim 与 pretty)
pointer.mbt RFC 6901
patch.mbt 原位编辑
*_test.mbt 70 个测试 / 89 份一致性文档
cmd/main/ CLI:check / stats / get / set / pretty
bench/main/ 吞吐、查询、深嵌套基准
bench/deep/ 与 core/json 的深嵌套成本对照Install
Download zipA non-recursive, zero-copy JSON kernel: exact integers, verbatim round-trip, span-based in-place editing.