silk.json.value.

Parse JSON into a tree of values, read fields from it, and write it back.

When to use#

Use Json.parse when the shape of a document is not fixed, or when you need only a few fields of a larger document. Use Json.parseExact when decimal precision matters: it retains number spellings without rounding. Both return the same tree. Read fields with Json.field, Json.fieldAt, and the as... functions. Use Json.deserialize or Json.decode for typed values and Json.serialize to write them. Use silk.json.scanner to read tokens without a tree.

Details#

Parsing is strict (RFC 8259): no comments, no trailing commas, and no duplicate keys in an object. Arrays and objects keep source order. String escapes are decoded. Json.parse keeps integers that fit in i64 or u64 exact and converts other numbers to the nearest f64. Json.parseExact keeps every number as a validated decimal spelling with no precision or exponent bound. If parsing fails, everything that was built is released.

Errors#

  • JsonError for invalid JSON, duplicate keys, nesting deeper than MAX_DEPTH (64), or trailing content. Json.parse also rejects numbers outside finite f64; Json.parseExact does not.

  • OutOfMemoryError if the Allocator cannot supply the tree.

  • WriterError from the write functions if the Writer fails.

Gotchas#

A borrowed field or string cannot live longer than the Value that owns it. The write functions do not flush the Writer.

Examples#

Read fields from a document#

silk
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.core.effect { Effect }
import silk.json.scanner { JsonError }
import silk.json.value { Json }
import silk.core.option { Option }

pub effect fn main() -> i32
  ! JsonError | OutOfMemoryError {
  let mut allocator = Allocator.systemAllocatorProvider()
  let document = run Json.parse(b"{\"id\":42,\"user\":{\"name\":\"Ada\"}}")
    |> Effect.provideMut<Allocator>(&mut allocator)
  let id = Json.field(&document, "id") |> Json.asI32 |> Option<i32>.unwrapOr(0)
  let name = Json.field(&document, "user") |> Json.fieldAt("name") |> Json.asString
    |> Option<string>.unwrapOr("")
  if id != 42 || name != "Ada" {
    return 1
  }
  return 0
}

Read a typed value directly#

silk
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.core.effect { Effect }
import silk.json.scanner { JsonError }
import silk.json.value { Json }
import silk.collections.list { List }

pub effect fn main() -> i32
  ! JsonError | OutOfMemoryError {
  let mut allocator = Allocator.systemAllocatorProvider()
  let values = run Json.deserialize<List<i64>>(b"[1, 2, 39]")
    |> Effect.provideMut<Allocator>(&mut allocator)
  if List<i64>.length(&values) != 3 {
    return 1
  }
  return 0
}

Import as Json with import silk.json.value { Json }.

Public declarations: 11.

JsonEntry#

silk
pub struct JsonEntry

One key and value of a JSON object.

Field key#

silk
pub key: String

The key, with escapes decoded.

Field value#

silk
pub value: Value

The value.

JsonNumber#

silk
pub union JsonNumber

An owned JSON number stored as a machine value or as an exact validated decimal spelling.

Details#

Json.parse stores an integer written without a fraction or exponent as Integer when it fits in i64, or Unsigned when it fits only in u64. Other numbers become Float, rounded to nearest f64 with ties to even. Json.parseExact stores all numbers as Decimal, retaining their source spelling without a precision or exponent bound. Decimal owns its text.

Gotchas#

Json.write rejects a Float that is not finite. Manually constructed Decimal values must contain a valid JSON number spelling. Borrow with JsonNumber.view instead of copying text.

Integer#

silk
Integer

An integer that fits in i64.

Field value#

silk
pub value: i64

The value.

Unsigned#

silk
Unsigned

An integer more than i64.MAX that fits in u64.

Field value#

silk
pub value: u64

The value.

Float#

silk
Float

A number with a fraction or an exponent, or an integer too large for u64.

Field value#

silk
pub value: f64

The nearest f64.

Decimal#

silk
Decimal

An exact decimal number retained without a precision or exponent bound by Json.parseExact.

Field text#

silk
pub text: String

A validated JSON number spelling. Manually constructed values must obey JSON number syntax.

JsonNumberView#

silk
pub union JsonNumberView<'text>

An allocation-free view of a JSON number from a tree or packed document. Decimal text borrows its owner; scalar variants copy their machine value.

Integer#

silk
Integer

A signed machine integer.

Field value#

silk
pub value: i64

The exact integer value.

Unsigned#

silk
Unsigned

An unsigned machine integer.

Field value#

silk
pub value: u64

The exact integer value.

Float#

silk
Float

A binary floating-point value.

Field value#

silk
pub value: f64

The stored f64; manually constructed trees can contain nonfinite values.

Decimal#

silk
Decimal

A validated JSON decimal spelling with no precision or exponent bound.

Field text#

silk
pub text: string<'text>

The number text, borrowed from the tree or document.

Implementation Copy for JsonNumberView<'text>#

silk
impl<'text> Copy for JsonNumberView<'text>

Implementation JsonNumber#

silk
impl JsonNumber

Method view#

silk
pub fn view<'a>(self: &'a Self) -> JsonNumberView<'a>

Borrows a number without allocating or copying owned decimal text. The returned decimal view cannot outlive self.

Implementation JsonNumberView<'text>#

silk
impl<'text> JsonNumberView<'text>

Method toOwned#

silk
pub effect fn toOwned(self: Self) -> JsonNumber ! OutOfMemoryError ? &mut Allocator

Copies a number into independently owned storage. Machine-number variants do not allocate.

Errors#

  • OutOfMemoryError if decimal text cannot be copied.

Value#

silk
pub union Value

One JSON value: null, a boolean, a number, a string, an array, or an object.

Details#

A Value owns all of its children. Use match to get the kind, or the Json.as... functions to read a field of a known kind. Arrays and objects keep source order. Json.parse converts numbers to machine values; Json.parseExact keeps exact decimal spellings in the same tree.

Gotchas#

A borrowed field or string cannot live longer than the Value that owns it.

Null#

silk
Null

JSON null.

Bool#

silk
Bool

JSON true or false.

Field value#

silk
pub value: bool

The boolean value.

Number#

silk
Number

A JSON number.

Field value#

silk
pub value: JsonNumber

The number, as a machine value or an owned exact decimal spelling.

String#

silk
String

A JSON string.

Field text#

silk
pub text: String

The text, with escapes decoded.

Array#

silk
Array

A JSON array.

Field values#

silk
pub values: List<Value>

The elements in source order.

Object#

silk
Object

A JSON object.

Field entries#

silk
pub entries: List<JsonEntry>

The members in source order.

Json#

silk
pub struct Json

The owner type of the JSON parse, write, and read operations. It has no fields and is never constructed.

Implementation Json#

silk
impl Json

Associated function copy#

silk
pub effect fn copy(value: &Value) -> Value ! OutOfMemoryError ? &mut Allocator

Copies a tree into independent owned storage, preserving object order and exact number text.

Errors#

  • OutOfMemoryError if the allocator cannot supply the copied tree.

Associated function parse#

silk
pub effect fn parse(bytes: &[u8]) -> Value ! JsonError | OutOfMemoryError ? &mut Allocator

Parses bytes as one complete JSON document and returns its tree.

When to use#

Use it when the shape of a document is not fixed, or when you need only a few fields of a larger document. To read a typed value, use Json.deserialize or Json.decode.

Details#

Parsing is strict (RFC 8259): no comments, no trailing commas, and no duplicate keys in an object. String escapes are decoded when the document is parsed.

Errors#

  • JsonError if bytes is not one valid JSON value, if an object has a duplicate key, if the nesting is deeper than 64, or if content follows the value. The partial tree is dropped.

  • OutOfMemoryError if the Allocator cannot supply the tree.

Associated function parseExact#

silk
pub effect fn parseExact(bytes: &[u8]) -> Value ! JsonError | OutOfMemoryError ? &mut Allocator

Parses one complete strict JSON document with every number retained as JsonNumber.Decimal. Numbers keep their validated source spelling without rounding or a fixed exponent bound. String decoding, duplicate-key checks, and the nesting limit are shared with Json.parse.

Errors#

  • JsonError for invalid JSON, duplicate decoded keys, excessive nesting, or trailing content.

  • OutOfMemoryError if the allocator cannot supply the owned tree and number text.

Associated function decode#

silk
pub fn decode<T: Decode>(bytes: &[u8]) -> Result<T, JsonError>

Reads bytes as one complete JSON document of type T. It does not allocate.

When to use#

Use it for types that implement Decode, such as numbers and bool. Use Json.deserialize for types that need memory, such as String and List<T>.

Errors#

  • JsonError if the JSON is not valid, the value does not have type T (TypeMismatch), a number does not fit (NumberOutOfRange), or content follows the value (TrailingContent).

Associated function deserialize#

silk
pub effect fn deserialize<T: Deserialize>(bytes: &[u8])
    -> T ! JsonError | OutOfMemoryError ? &mut Allocator

Reads bytes as one complete JSON document of type T.

Errors#

  • JsonError if the JSON is not valid, the value does not have type T, or content follows the value.

  • OutOfMemoryError if the Allocator cannot supply the value.

Associated function serialize#

silk
pub effect fn serialize<T: Serialize>(value: &T, options: &JsonOptions)
    -> () ! JsonError | WriterError ? &mut Writer

Writes value as JSON to the Writer, with options.

Errors#

  • JsonError if the nesting is deeper than the limit in options, or a float is not finite.

  • WriterError if the Writer fails. Bytes that it accepted before the failure stay written.

Examples#

Write a struct#

silk
import silk.core.effect { Effect }
import silk.json.codec { Serialize }
import silk.json.object { JsonObject }
import silk.json.output { JsonOptions }
import silk.json.scanner { JsonError }
import silk.json.value { Json }
import silk.io.writer { Writer, WriterError }

struct CaptureWriter {
  bytes: [u8; 64],
  length: usize,
}

impl Writer for CaptureWriter {
  effect fn writeAll(self: &mut Self, value: &[u8]) -> ()
    ! WriterError
    ? &mut Writer {
    let mut index: usize = 0
    while index < value.length {
      self.bytes[self.length] = value[index]
      self.length = self.length + 1
      index = index + 1
    }
    return ()
  }

  effect fn flush(self: &mut Self) -> ()
    ! WriterError
    ? &mut Writer {
    return ()
  }
}

fn holds(writer: &CaptureWriter, expected: &[u8]) -> bool {
  if writer.length != expected.length {
    return false
  }
  let mut index: usize = 0
  while index < expected.length {
    if writer.bytes[index] != expected[index] {
      return false
    }
    index = index + 1
  }
  return true
}

struct Point {
  x: i32,
  y: i32,
}

impl Serialize for Point {
  effect fn serialize(self: &Self, options: &JsonOptions) -> ()
    ! JsonError | WriterError
    ? &mut Writer {
    return run JsonObject.begin(options) |> JsonObject.field("x", &self.x)
      |> JsonObject.field("y", &self.y)
      |> JsonObject.end
  }
}

pub effect fn main() -> i32
  ! JsonError | WriterError {
  let mut writer = CaptureWriter { bytes: [0; 64], length: 0 }
  let point = Point { x: 3, y: -4 }
  run Json.serialize(&point, &JsonOptions.compact()) |> Effect.provideMut<Writer>(&mut writer)
  if !holds(&writer, b"{\"x\":3,\"y\":-4}") {
    return 1
  }
  return 0
}

Associated function write#

silk
pub effect fn write(document: &Value) -> () ! JsonError | WriterError ? &mut Writer

Writes document as compact JSON to the Writer. It does not flush the Writer.

Errors#

  • JsonError if the nesting is deeper than 64.

  • WriterError if the Writer fails.

Gotchas#

The text goes to the Writer in pieces of up to 4 KiB. After a failure, the Writer holds only the pieces passed to it before the failure.

Associated function writeWith#

silk
pub effect fn writeWith(document: &Value, options: &JsonOptions)
    -> () ! JsonError | WriterError ? &mut Writer

Writes document as JSON to the Writer, with the indentation and depth limit of options. It does not flush the Writer.

Errors#

  • JsonError if the nesting is deeper than the limit in options.

  • WriterError if the Writer fails.

Gotchas#

The text goes to the Writer in pieces of up to 4 KiB. After a failure, the Writer holds only the pieces passed to it before the failure.

Method field#

silk
pub fn field<'a>(self: &'a Value, key: string) -> Option<&'a Value>

Returns the value of member key of an object. Returns an absent option if self is not an object or has no such key.

Method fieldAt#

silk
pub fn fieldAt<'a>(self: Option<&'a Value>, key: string) -> Option<&'a Value>

Returns the value of member key if self is a present object. Returns an absent option in other cases.

When to use#

Use it to read nested fields in a chain: Json.field(&doc, "user") |> Json.fieldAt("name").

Method asI32#

silk
pub fn asI32(self: Option<&Value>) -> Option<i32>

Returns an integer-spelled number as i32, accepting machine integers and exact decimals. Returns None for an absent value, a fraction or exponent spelling, a float, or overflow.

Method asI64#

silk
pub fn asI64(self: Option<&Value>) -> Option<i64>

Returns an integer-spelled number as i64, accepting signed machine integers and decimals. Returns None for an absent value, a fraction or exponent spelling, a float, or overflow.

Method asU64#

silk
pub fn asU64(self: Option<&Value>) -> Option<u64>

Returns an integer-spelled number as u64, accepting machine integers and exact decimals. Returns None for an absent value, a negative or noninteger spelling, a float, or overflow.

Method asF64#

silk
pub fn asF64(self: Option<&Value>) -> Option<f64>

Returns the number as f64, rounded to the nearest value. Returns an absent option if the value is absent, is not a number, or is not finite.

Method asF32#

silk
pub fn asF32(self: Option<&Value>) -> Option<f32>

Returns the number as f32, rounded to the nearest value. Returns an absent option if the value is absent, is not a number, or is too large for a finite f32.

Gotchas#

A Float was already rounded to f64 when the document was parsed, so it is rounded two times.

Method asString#

silk
pub fn asString<'a>(self: Option<&'a Value>) -> Option<string<'a>>

Returns the text of a string. Returns an absent option if the value is absent or is not a string. The text is borrowed from the tree.

Associated function item#

silk
pub fn item<'a>(value: &'a Value, index: usize) -> Option<&'a Value>

Returns the zero-based array element, or None for a non-array or an out-of-range index. The returned value borrows the input tree and cannot outlive it.

Associated function equal#

silk
pub fn equal(left: &Value, right: &Value) -> bool

Compares JSON values without allocating. Numbers compare mathematically, arrays compare in order, and objects compare by decoded key regardless of insertion order. Object keys must be unique. A nonfinite machine number compares unequal to every value, including itself. Finite floats are interpreted using their shortest round-tripping decimal spelling.

Associated function numberIsFinite#

silk
pub fn numberIsFinite(value: &JsonNumber) -> bool

Returns false only for a machine float that is NaN or an infinity. Exact decimal spellings are finite mathematical numbers even when their exponents are huge.

Associated function compareNumbers#

silk
pub fn compareNumbers(left: &JsonNumber, right: &JsonNumber) -> i32

Returns -1, 0, or 1 according to the mathematical order of two finite JSON numbers. Decimal and integer variants remain exact. Floats use their shortest round-tripping decimal spelling. No heap storage is needed. Both numbers must be finite; otherwise this traps.

Associated function isIntegerNumber#

silk
pub fn isIntegerNumber(value: &JsonNumber) -> bool

Returns whether a finite JSON number is mathematically integral without allocating. Decimal and integer variants remain exact; floats use their shortest round-tripping decimal spelling. The number must be finite; otherwise this traps.

Associated function multipleOfNumbers#

silk
pub effect fn multipleOfNumbers(value: &JsonNumber, divisor: &JsonNumber) -> bool
    ! OutOfMemoryError ? &mut Allocator

Returns whether a finite JSON number is an exact integer multiple of a positive divisor. Returns false for nonpositive divisors. Decimal and integer variants remain exact; floats use their shortest round-tripping decimal spelling. Both numbers must be finite.

Errors#

  • OutOfMemoryError if decimal arithmetic scratch storage cannot be allocated.

Gotchas#

Traps for a NaN or infinite machine-number argument.

Associated function asUsizeNumber#

silk
pub fn asUsizeNumber(value: &JsonNumber) -> Option<usize>

Converts a finite JSON number to usize if nonnegative, integral, and in range. Returns None for fractions, negatives, or overflow. Negative zero becomes zero. Floats use their shortest round-tripping decimal spelling. No allocation is needed. The number must be finite; otherwise this traps.

Implementation Serialize for Value#

silk
impl Serialize for Value

Operation serialize#

silk
effect fn serialize(self: &Self, options: &JsonOptions)
    -> () ! JsonError | WriterError ? &mut Writer

Implementation Deserialize for Value#

silk
impl Deserialize for Value

Operation deserialize#

silk
effect fn deserialize(scanner: &mut JsonScanner<'_>)
    -> Self ! JsonError | OutOfMemoryError ? &mut Allocator

JsonDocument#

silk
pub struct JsonDocument

A parsed JSON document kept in two flat buffers: one record for each value, in source order, and the decoded text of every string and key.

When to use#

Use it to read a document. Parsing allocates about two buffers in all, instead of one for each string, array, and object as Json.parse does, and dropping it frees only those buffers. Use a Value tree when you need to build or change a document; JsonDocument.toValue makes one.

Details#

A value is named by a JsonNode, a position in its document. An array record is followed by its elements, and an object record by each key and its value, so a node's children are the records after it. Each array and object knows where its last child ends, so skipping a value is one step.

Gotchas#

A JsonNode is only meaningful with the document that returned it. With another document it names some other value or traps.

Examples#

Read fields of a parsed document#

silk
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.core.effect { Effect }
import silk.core.option { Option }
import silk.json.scanner { JsonError }
import silk.json.value { JsonDocument, JsonNode }

effect fn read() -> i32 ! JsonError | OutOfMemoryError ? &mut Allocator {
  let document = run JsonDocument.parse(b"{\"name\":\"Ada\",\"tags\":[1,2,3]}")
  let root = JsonDocument.root(&document)
  let tags = match JsonDocument.field(&document, root, "tags") {
    Option<JsonNode>.Some { value } => value
    Option<JsonNode>.None => { return 1 }
  }
  if JsonDocument.length(&document, tags) != 3 {
    return 2
  }
  let name = match JsonDocument.field(&document, root, "name") {
    Option<JsonNode>.Some { value } => value
    Option<JsonNode>.None => { return 3 }
  }
  return match JsonDocument.asString(&document, name) {
    Option<string>.Some { value } => if value == "Ada" { 0 } else { 4 }
    Option<string>.None => 4
  }
}

effect fn program() -> i32 ! JsonError | OutOfMemoryError {
  let mut allocator = Allocator.systemAllocatorProvider()
  return run read() |> Effect.provideMut<Allocator>(&mut allocator)
}

effect fn failed(error: JsonError | OutOfMemoryError) -> i32 {
  return 5
}

pub fn main() -> i32 {
  return run Effect.catchAll(program(), failed)
}

JsonNode#

silk
pub struct JsonNode

One value in a JsonDocument: its position in the document.

Implementation Copy for JsonNode#

silk
impl Copy for JsonNode

JsonKind#

silk
pub enum JsonKind

The kind of a value in a JsonDocument.

Null#

silk
Null

JSON null.

Bool#

silk
Bool

JSON true or false.

Number#

silk
Number

A JSON number.

String#

silk
String

A JSON string.

Array#

silk
Array

A JSON array.

Object#

silk
Object

A JSON object.

JsonMember#

silk
pub struct JsonMember

One member of an object in a JsonDocument: the node of its key, which is a string, and the node of its value.

Field key#

silk
pub key: JsonNode

The key, a string node.

Field value#

silk
pub value: JsonNode

The value.

Implementation Copy for JsonMember#

silk
impl Copy for JsonMember

JsonItems#

silk
pub struct JsonItems

The elements of an array in a JsonDocument, in source order. JsonDocument.items makes it.

JsonMembers#

silk
pub struct JsonMembers

The members of an object in a JsonDocument, in source order. JsonDocument.members makes it.

Implementation JsonItems#

silk
impl JsonItems

Method next#

silk
pub fn next(self: &mut Self, document: &JsonDocument) -> Option<JsonNode>

Returns the next element, or an absent option after the last one. document must be the one that made these items.

Implementation JsonMembers#

silk
impl JsonMembers

Method next#

silk
pub fn next(self: &mut Self, document: &JsonDocument) -> Option<JsonMember>

Returns the next member, or an absent option after the last one. document must be the one that made these members.

Implementation JsonDocument#

silk
impl JsonDocument

Associated function parse#

silk
pub effect fn parse(bytes: &[u8]) -> JsonDocument ! JsonError | OutOfMemoryError ? &mut Allocator

Parses bytes as one complete JSON document.

Details#

Parsing is strict (RFC 8259), with the same rules and errors as Json.parse: no comments, no trailing commas, no duplicate keys, nesting at most 64 deep, and nothing after the value. String escapes are decoded when the document is parsed, and numbers are converted to a JsonNumber.

Errors#

  • JsonError if bytes is not one valid JSON value, with the reason and offset that Json.parse reports.

  • OutOfMemoryError if the Allocator cannot supply the buffers.

Associated function fromValue#

silk
pub effect fn fromValue(value: &Value) -> JsonDocument ! OutOfMemoryError ? &mut Allocator

Returns a document that holds a copy of value.

Errors#

  • OutOfMemoryError if the Allocator cannot supply the buffers.

Method root#

silk
pub fn root(self: &Self) -> JsonNode

Returns the node of the whole document.

Method kind#

silk
pub fn kind(self: &Self, node: JsonNode) -> JsonKind

Returns the kind of node.

Method asBool#

silk
pub fn asBool(self: &Self, node: JsonNode) -> Option<bool>

Returns the value of a boolean. Returns an absent option if node is not a boolean.

Method asNumber#

silk
pub fn asNumber<'a>(self: &'a Self, node: JsonNode) -> Option<JsonNumberView<'a>>

Returns a borrowed view of a number, or None if node is not a number. This operation does not allocate. Decimal text borrows the document and cannot outlive it.

Method asString#

silk
pub fn asString<'a>(self: &'a Self, node: JsonNode) -> Option<string<'a>>

Returns the text of a string, with escapes decoded. Returns an absent option if node is not a string. The text is borrowed from the document.

Method length#

silk
pub fn length(self: &Self, node: JsonNode) -> usize

Returns the number of elements of an array or members of an object, or 0 for any other value.

Method items#

silk
pub fn items(self: &Self, node: JsonNode) -> JsonItems

Returns the elements of an array, or no elements if node is not an array.

Method members#

silk
pub fn members(self: &Self, node: JsonNode) -> JsonMembers

Returns the members of an object, or no members if node is not an object.

Method field#

silk
pub fn field(self: &Self, node: JsonNode, key: string) -> Option<JsonNode>

Returns the value of member key of an object. Returns an absent option if node is not an object or has no such key.

Method toValue#

silk
pub effect fn toValue(self: &Self, node: JsonNode) -> Value ! OutOfMemoryError ? &mut Allocator

Returns a Value tree that holds a copy of node and everything in it.

Errors#

  • OutOfMemoryError if the Allocator cannot supply the tree.

Method write#

silk
pub effect fn write(self: &Self) -> () ! JsonError | WriterError ? &mut Writer

Writes the document as compact JSON to the Writer. It does not flush the Writer.

Errors#

  • JsonError with reason InvalidNumber for a float that is not finite, which only JsonDocument.fromValue can store.

  • WriterError if the Writer fails.

Gotchas#

The text goes to the Writer in pieces of up to 4 KiB. After a failure, the Writer holds only the pieces passed to it before the failure.

Method writeWith#

silk
pub effect fn writeWith(self: &Self, options: &JsonOptions) -> () ! JsonError | WriterError ? &mut Writer

Writes the document as JSON to the Writer, with the indentation and depth limit of options. It does not flush the Writer.

Errors#

  • JsonError if the nesting is deeper than the limit in options, or with reason InvalidNumber for a float that is not finite.

  • WriterError if the Writer fails.

Category: Data formats.

Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.

View the source of this page