silk.schema.json.

Read and write Schema types as JSON.

When to use#

Call SchemaJson.decode to read a value of a silk.schema.schema.Schema type from JSON text, SchemaJson.decodeAll to report every problem in the text at once, and SchemaJson.encode to write a value to the ambient Writer. Show the problems with silk.schema.report.SchemaReport. Use silk.json.value.Json to work with a JSON document whose shape is not known in advance.

Details#

Decoding streams over the text with silk.json.scanner.JsonScanner and builds the value directly, with no tree of JSON values in between. Each object is scanned once into an index of its members, so members may come in any order, and members the type does not name are skipped, or reported when its spec is Spec.strict. Every problem carries the span of the bytes it is about. Encoding writes compact JSON, with struct fields in declaration order. A silk.collections.bytes.Bytes field is a string in standard Base64 with padding.

Examples#

Report where a value failed#

silk
import silk.collections.list { List }
import silk.core.effect { Effect }
import silk.core.result { Result }
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.schema.issue { IssueReason, SchemaError }
import silk.schema.json { SchemaJson }
import silk.schema.schema { Schema }
import silk.text.string { String }

struct Limits {
  pub ports: List<u16>,
}

impl Schema for Limits {}

effect fn check() -> i32 ! OutOfMemoryError ? &mut Allocator {
  return match move run Effect.result(SchemaJson.decode<Limits>(b"{\"ports\": [80, 70000]}")) {
    Result<Limits, SchemaError | OutOfMemoryError>.Success {..} => 1
    Result<Limits, SchemaError | OutOfMemoryError>.Failure {error} => match move error {
      SchemaError {path, issue, ..} => {
        let pointer = run path.pointer()
        if pointer.view() == "/ports/1" && issue.reason == IssueReason.InvalidValue { 0 } else { 2 }
      }
      OutOfMemoryError {} => 3
    }
  }
}

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

Import as SchemaJson with import silk.schema.json { SchemaJson }.

Public declarations: 3.

SchemaJson#

silk
pub struct SchemaJson

The owner of the JSON entry points. It has no fields and is never constructed.

Implementation SchemaJson#

silk
impl SchemaJson

Associated function decode#

silk
pub effect fn decode<T: Schema>(bytes: &[u8]) -> T
    ! SchemaError | OutOfMemoryError
    ? &mut Allocator

Reads one value of type T from the JSON text bytes, stopping at the first problem.

Details#

The whole input must be one JSON value, with optional white space around it.

Errors#

  • SchemaError if the text is not valid JSON or does not hold a T. Its path names the part that failed, and its issue has the span of the bytes it is about.

  • OutOfMemoryError if the Allocator cannot supply the value.

Associated function decodeTagged#

silk
pub effect fn decodeTagged<T: Schema>(bytes: &[u8]) -> T
    ! SchemaError | OutOfMemoryError
    ? &mut Allocator

Reads JSON with options encoded as [false] or [true, value], preserving nested options. An absent optional record field still decodes to None.

Associated function decodeAll#

silk
pub effect fn decodeAll<T: Schema>(bytes: &[u8]) -> T
    ! SchemaErrors | OutOfMemoryError
    ? &mut Allocator

Reads one value of type T from the JSON text bytes, reporting every problem.

Details#

A field, element or variant that fails is recorded and skipped, and reading goes on with the next one, so one call lists every problem, in input order: a missing key, a wrong type, a number out of range and a failed rule alike. Text that is not valid JSON is the one problem reported. At most MAX_PROBLEMS (64) are listed.

Errors#

  • SchemaErrors with every problem found.

  • OutOfMemoryError if the Allocator cannot supply the value.

Associated function decodeVariant#

silk
pub effect fn decodeVariant<U: Schema>(name: string, bytes: &[u8]) -> U
    ! SchemaErrors | OutOfMemoryError
    ? &mut Allocator

Reads the variant of the union U whose wire name is name from the JSON object bytes of its fields, reporting every problem.

When to use#

Read a call whose name and arguments arrive apart, such as a tool call from a model, into the union whose variants are the tools.

Errors#

  • SchemaErrors with every problem found, as decodeAll reports them, or IssueReason.UnknownVariant if U has no variant name.

  • OutOfMemoryError if the Allocator cannot supply the value.

Associated function encode#

silk
pub effect fn encode<T: Schema>(value: &T) -> ()
    ! SchemaError | WriterError | OutOfMemoryError
    ? &mut Writer | &mut Allocator

Writes value as compact JSON to the ambient Writer.

Errors#

  • SchemaError if JSON cannot hold the value, such as a NaN or an infinity, or a value nested more than 64 levels deep. Its path is empty.

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

  • OutOfMemoryError if a codec needs memory that the Allocator cannot supply.

Associated function encodeTagged#

silk
pub effect fn encodeTagged<T: Schema>(value: &T) -> ()
    ! SchemaError | WriterError | OutOfMemoryError
    ? &mut Writer | &mut Allocator

Writes options as [false] or [true, value], preserving nested options. Optional record fields holding None remain omitted.

JsonSchemaReader#

silk
pub struct JsonSchemaReader<'input>

A SchemaReader over JSON text.

When to use#

SchemaJson.decode uses it. Use it directly to read a value from the middle of a larger program's own JSON handling.

Implementation JsonSchemaReader<'input>#

silk
impl<'input> JsonSchemaReader<'input>

Associated function make#

silk
pub fn make(input: &'input [u8]) -> JsonSchemaReader<'input>

Returns a reader at the start of input.

Associated function collectingAll#

silk
pub fn collectingAll(input: &'input [u8]) -> JsonSchemaReader<'input>

Returns a reader at the start of input that records every problem instead of stopping at the first. Read them with JsonSchemaReader.intoErrors.

Method intoErrors#

silk
pub fn intoErrors(self: Self) -> List<SchemaError>

Returns the problems the reader recorded, in the order they were found.

Implementation JsonSchemaReader<'input>#

silk
impl<'input> JsonSchemaReader<'input>

Implementation SchemaReader for JsonSchemaReader<'input>#

silk
impl<'input> SchemaReader for JsonSchemaReader<'input>

Operation taggedOptions#

silk
fn taggedOptions(self: &Self) -> bool

Operation path#

silk
fn path(self: &mut Self) -> &mut SchemaPath

Returns the path of the part being read.

Operation report#

silk
effect fn report(self: &mut Self, issue: Issue) -> ()
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Fails with the issue, or records it and returns when the reader collects every problem.

Operation collecting#

silk
fn collecting(self: &Self) -> bool

Returns whether the reader records every problem.

Operation lastSpan#

silk
fn lastSpan(self: &Self) -> Option<Span>

Returns the span of the last complete value read.

Operation lastKind#

silk
fn lastKind(self: &Self) -> ValueKind

Returns the kind of the last complete value read.

Operation mark#

silk
effect fn mark(self: &mut Self) -> usize
    ! OutOfMemoryError
    ? &mut Allocator

Remembers the open objects and lists and the scanner's position.

Operation recover#

silk
effect fn recover(self: &mut Self, mark: usize, skip: bool) -> ()
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Returns to the mark, closing the objects and lists opened since, and reads past the value there when skip is true.

Operation release#

silk
fn release(self: &mut Self, mark: usize) -> ()

Forgets the mark and every later one.

Operation boolean#

silk
effect fn boolean(self: &mut Self) -> bool
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Reads true or false.

Operation signed#

silk
effect fn signed(self: &mut Self) -> i64
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Reads a JSON number as an i64.

Operation unsigned#

silk
effect fn unsigned(self: &mut Self) -> u64
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Reads a JSON number as a u64.

Operation float#

silk
effect fn float(self: &mut Self) -> f64
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Reads a JSON number as an f64.

Operation text#

silk
effect fn text(self: &mut Self) -> String
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Reads a JSON string, with its escapes decoded.

Operation null#

silk
effect fn null(self: &mut Self) -> bool
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Reads past null and returns true, or returns false for another value.

Operation beginList#

silk
effect fn beginList(self: &mut Self) -> ()
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Reads past [.

Operation nextElement#

silk
effect fn nextElement(self: &mut Self) -> bool
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Returns true at the next element, or reads past ] and returns false.

Operation beginObject#

silk
effect fn beginObject(self: &mut Self) -> ()
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Reads the object's members into an index once, so member finds each without scanning.

Operation member#

silk
effect fn member(self: &mut Self, key: string) -> bool
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Finds the member key in the object's index and leaves the reader at its value. A missing key leaves the object's opening brace as the last span.

Operation nextMember#

silk
effect fn nextMember(self: &mut Self) -> Option<String>
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Operation rejectUnread#

silk
effect fn rejectUnread(self: &mut Self, expected: string<'static>) -> ()
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Reports every member no member call found, at its key.

Operation endObject#

silk
effect fn endObject(self: &mut Self) -> ()
    ! Issue | OutOfMemoryError
    ? &mut Allocator

Jumps past the whole object being read.

JsonSchemaWriter#

silk
pub struct JsonSchemaWriter

A SchemaWriter that writes compact JSON to the ambient Writer.

When to use#

SchemaJson.encode uses it. Use it directly to write a value inside JSON that the program writes itself.

Implementation JsonSchemaWriter#

silk
impl JsonSchemaWriter

Associated function make#

silk
pub fn make() -> JsonSchemaWriter

Returns a writer for one top-level value.

Implementation SchemaWriter for JsonSchemaWriter#

silk
impl SchemaWriter for JsonSchemaWriter

Operation taggedOptions#

silk
fn taggedOptions(self: &Self) -> bool

Operation boolean#

silk
effect fn boolean(self: &mut Self, value: bool) -> ()
    ! Issue | WriterError
    ? &mut Writer

Writes true or false.

Operation signed#

silk
effect fn signed(self: &mut Self, value: i64) -> ()
    ! Issue | WriterError
    ? &mut Writer

Writes the integer in decimal.

Operation unsigned#

silk
effect fn unsigned(self: &mut Self, value: u64) -> ()
    ! Issue | WriterError
    ? &mut Writer

Writes the integer in decimal.

Operation float#

silk
effect fn float(self: &mut Self, value: f64) -> ()
    ! Issue | WriterError
    ? &mut Writer

Writes the number. A NaN or an infinity fails with IssueReason.InvalidValue.

Operation text#

silk
effect fn text(self: &mut Self, value: string) -> ()
    ! Issue | WriterError
    ? &mut Writer

Writes a JSON string, with the escapes JSON needs.

Operation null#

silk
effect fn null(self: &mut Self) -> ()
    ! Issue | WriterError
    ? &mut Writer

Writes null.

Operation beginList#

silk
effect fn beginList(self: &mut Self, count: usize) -> ()
    ! Issue | WriterError
    ? &mut Writer

Writes [. JSON does not write count.

Operation element#

silk
effect fn element(self: &mut Self) -> ()
    ! Issue | WriterError
    ? &mut Writer

Writes , before every element but the first.

Operation endList#

silk
effect fn endList(self: &mut Self) -> ()
    ! Issue | WriterError
    ? &mut Writer

Writes ].

Operation beginObject#

silk
effect fn beginObject(self: &mut Self, count: usize) -> ()
    ! Issue | WriterError
    ? &mut Writer

Writes {. JSON does not write count.

Operation key#

silk
effect fn key(self: &mut Self, name: string) -> ()
    ! Issue | WriterError
    ? &mut Writer

Writes , before every member but the first, then the key and :.

Operation endObject#

silk
effect fn endObject(self: &mut Self) -> ()
    ! Issue | WriterError
    ? &mut Writer

Writes }.

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