library/json.md
- Repository
- guillermomolina/protos
- Commit
379c6fa63685c39a5954cfbd577bfda3b4df8e75- Tree
8cd4f4afe29ae4c3866381f38c1858108e9799f6- Blob
3a40a3232edf0e2d7a7c241578fb4b52038588c3- Source
- View exact source on GitHub
JSON
std:json/json reads and writes JSON as a tree of semantic nodes. It does
not convert JSON into arbitrary Protos objects, and it never turns numbers into
binary Floats: your program decides what each node means. This guide is
non-normative; the module documentation in
protos/lib/json/json/module.protos
and its conformance corpus are the authority for exact behavior.
JSON: import("std:json/json")
A minimal example
JSON: import("std:json/json")
order: JSON.parse("{\"id\":\"A-17\",\"total\":19.90}")
order.value["id"].value // "A-17"
order.value["total"].value.coefficient // 1990
order.value["total"].value.exponent // -2
JSON.encode(JSON.object("ok", JSON.boolean(true))) // {"ok":true}
The data model
Every node is a fresh object with two slots, kind and value:
| Constructor | kind | value |
|---|---|---|
JSON.nullValue() | "null" | null |
JSON.boolean(value) | "boolean" | canonical true or false |
JSON.string(value) | "string" | a String |
JSON.number(coefficient, exponent) | "number" | { coefficient, exponent }, both Integers |
JSON.array(...nodes) | "array" | an Array of nodes |
JSON.object(name, node, ...) | "object" | a Map from names to nodes, in member order |
- Exact numbers. A number is
coefficient × 10^exponent. The parser keeps the written precision (19.90is1990,-2;-12.30e-2is-1230,-4). Convert to an Integer, Fraction or Float yourself when your application needs one. - Ordered members. Object members keep document or construction order;
iterate with
node.value.each((name, child) => ...). - Duplicate names are rejected by
object,parseand the incremental parser and writer. A non-String name, a non-node value or a missing final value also signals an Error.
Complete documents
JSON.parse(text)parses one complete JSON text into a node tree. Malformed text, trailing content or a duplicate name signals an Error.JSON.encode(root)answers compact JSON text. An invalid node or a cyclic tree signals an Error; a subtree shared twice (without a cycle) is encoded twice. Numbers are written from coefficient and exponent, for exampleJSON.number(123, -2)encodes as123e-2andJSON.number(42, 0)as42.
A configuration-style example — read a document, build a new tree from parts of it, and serialize:
config: JSON.parse("{\"name\":\"api\",\"replicas\":3}")
updated: JSON.object(
"name", config.value["name"],
"replicas", JSON.number(config.value["replicas"].value.coefficient + 1, 0)
)
JSON.encode(updated) // {"name":"api","replicas":4}
Incremental events
JSON.eventParser(emit) answers a parser with feed(text) and finish().
Text may be split anywhere, even inside a literal, a name or a number. The
parser calls emit(event) in document order with records { kind, value }:
kind | value |
|---|---|
objectStart, objectEnd, arrayStart, arrayEnd | null |
name | the member name |
null | null |
boolean, string | the value |
number | { coefficient, exponent } |
finish() requires exactly one complete document. Malformed input, a failing
emit, or any use after finish() signals an Error and leaves the parser
terminal: every later call fails too.
JSON.eventWriter(emit) is the inverse: feed(event) accepts the same events
and calls emit(text) with encoded chunks; finish() requires one complete
document. An invalid event sequence (including a duplicate name) makes it
terminal in the same way. Piping a parser into a writer re-encodes a document
without building a tree.
Text I/O composition
The adapters compose with explicit, already acquired text capabilities; they never open files or sockets:
JSON.readEvents(textReader, emit)answers an adapter whoseread()reads one chunk withreadText(), feeds it to an event parser and answers a Future oftrue, or offalseonce input ended and the parser finished. Only oneread()may be pending.JSON.writeEvents(textWriter)answers an adapter whosefeed(event)andfinish()answer Futures of the adapter;finish()validates completion and performs one ordered zero-length write.
Both adapters borrow their reader or writer: they do not close, flush or
take ownership of it. Observe every Future (.value()) before relying on the
effect, and close the underlying resource yourself. See the
I/O guide for obtaining TextReaders and TextWriters.
Boundaries
- There is no automatic object mapping, schema validation or pretty printer.
- Encoding is always compact; whitespace in the input is not preserved.
- Importing the module grants no authority.
Learn more
- Tutorials:
15-structured-data/01-json-tree.protosand15-structured-data/02-json-events.protos. - Cookbook:
examples/data/json-report.protos. - Behavioral witnesses:
protos/tests/conformance/library/json/.