Skip to content

std.json

rfc 8259; parse into an arena tree, write with Out

pub JsonError :: errors {
unexpected_end,
unexpected_byte,
bad_number,
bad_string,
too_deep,
trailing_text,
}
  • unexpected_end: the text ends inside a value
  • unexpected_byte: a byte that cannot stand where it stands
  • bad_string: bad escape or control char in a string
  • too_deep: arrays and objects nested deeper than 512
  • trailing_text: something after the value
pub Kind :: enum {
null_value,
boolean,
number,
string,
array,
object,
}
pub Value :: struct {
kind: Kind,
flag: bool,
number: f64,
text: []const u8,
items: []Value,
keys: [][]const u8,
}
  • flag: the value of a boolean
  • number: the value of a number
  • text: string value, or a number’s source text
  • items: array elements or object member values
  • keys: object member names, parallel to items
pub get :: fn(self: Self, key: []const u8) -> Value

first member named key; null value if none or not an object

pub at :: fn(self: Self, i: usize) -> Value

null value past the end or if not an array

pub len :: fn(self: Self) -> usize

elements or members; 0 for anything else

pub is_null :: fn(self: Self) -> bool
pub as_f64 :: fn(self: Self) -> ?f64
pub as_i64 :: fn(self: Self) -> ?i64

whole numbers that fit i64; exact over the full range

pub as_text :: fn(self: Self) -> ?[]const u8
pub as_bool :: fn(self: Self) -> ?bool
pub null_value :: fn() -> Value

also what failed lookups return, so lookup chains need no checks

pub parse :: fn(text: []const u8, a: *Arena) -> Value ! JsonError

tree in a; skips a utf-8 bom; escape-free strings slice text; max depth 512

pub Out :: struct {
w: *Writer,
indent: usize,
depth: usize,
first: bool,
after_key: bool,
failed: bool,
}

streaming writer; does commas, quotes, escapes; write errors show in finish

  • indent: spaces a level; 0 writes it all on one line
  • first: nothing written yet at this depth
  • after_key: a key was written: its value comes next
pub begin_object :: fn(self: *Self)
pub end_object :: fn(self: *Self)
pub begin_array :: fn(self: *Self)
pub end_array :: fn(self: *Self)
pub key :: fn(self: *Self, name: []const u8)

next member’s name; write its value right after

pub string :: fn(self: *Self, s: []const u8)
pub int :: fn(self: *Self, v: i64)
pub uint :: fn(self: *Self, v: u64)
pub float :: fn(self: *Self, v: f64)

up to 15 significant digits; NaN/inf written as null

pub boolean :: fn(self: *Self, v: bool)
pub null_value :: fn(self: *Self)
pub value :: fn(self: *Self, v: Value)

whole tree; numbers written as they were read

pub finish :: fn(self: *Self) -> void ! IoError

.write_failed if any write failed

pub writer :: fn(w: *Writer) -> Out

single line

pub pretty :: fn(w: *Writer, indent: usize) -> Out

one member/element per line, indent spaces per level

pub stringify :: fn(a: *Arena, v: Value) -> []const u8

one line, in a