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#
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#
pub struct SchemaJsonThe owner of the JSON entry points. It has no fields and is never constructed.
Implementation SchemaJson#
impl SchemaJsonAssociated function decode#
pub effect fn decode<T: Schema>(bytes: &[u8]) -> T
! SchemaError | OutOfMemoryError
? &mut AllocatorReads 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#
SchemaErrorif the text is not valid JSON or does not hold aT. Itspathnames the part that failed, and its issue has the span of the bytes it is about.OutOfMemoryErrorif theAllocatorcannot supply the value.
Associated function decodeTagged#
pub effect fn decodeTagged<T: Schema>(bytes: &[u8]) -> T
! SchemaError | OutOfMemoryError
? &mut AllocatorReads JSON with options encoded as [false] or [true, value], preserving nested options.
An absent optional record field still decodes to None.
Associated function decodeAll#
pub effect fn decodeAll<T: Schema>(bytes: &[u8]) -> T
! SchemaErrors | OutOfMemoryError
? &mut AllocatorReads 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#
SchemaErrorswith every problem found.OutOfMemoryErrorif theAllocatorcannot supply the value.
Associated function decodeVariant#
pub effect fn decodeVariant<U: Schema>(name: string, bytes: &[u8]) -> U
! SchemaErrors | OutOfMemoryError
? &mut AllocatorReads 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#
SchemaErrorswith every problem found, asdecodeAllreports them, orIssueReason.UnknownVariantifUhas no variantname.OutOfMemoryErrorif theAllocatorcannot supply the value.
Associated function encode#
pub effect fn encode<T: Schema>(value: &T) -> ()
! SchemaError | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites value as compact JSON to the ambient Writer.
Errors#
SchemaErrorif 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.WriterErrorif theWriterfails. Bytes that it accepted before the failure stay written.OutOfMemoryErrorif a codec needs memory that theAllocatorcannot supply.
Associated function encodeTagged#
pub effect fn encodeTagged<T: Schema>(value: &T) -> ()
! SchemaError | WriterError | OutOfMemoryError
? &mut Writer | &mut AllocatorWrites options as [false] or [true, value], preserving nested options.
Optional record fields holding None remain omitted.
JsonSchemaReader#
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>#
impl<'input> JsonSchemaReader<'input>Associated function make#
pub fn make(input: &'input [u8]) -> JsonSchemaReader<'input>Returns a reader at the start of input.
Associated function collectingAll#
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#
pub fn intoErrors(self: Self) -> List<SchemaError>Returns the problems the reader recorded, in the order they were found.
Implementation JsonSchemaReader<'input>#
impl<'input> JsonSchemaReader<'input>Implementation SchemaReader for JsonSchemaReader<'input>#
impl<'input> SchemaReader for JsonSchemaReader<'input>Operation taggedOptions#
fn taggedOptions(self: &Self) -> boolOperation path#
fn path(self: &mut Self) -> &mut SchemaPathReturns the path of the part being read.
Operation report#
effect fn report(self: &mut Self, issue: Issue) -> ()
! Issue | OutOfMemoryError
? &mut AllocatorFails with the issue, or records it and returns when the reader collects every problem.
Operation collecting#
fn collecting(self: &Self) -> boolReturns whether the reader records every problem.
Operation lastSpan#
fn lastSpan(self: &Self) -> Option<Span>Returns the span of the last complete value read.
Operation lastKind#
fn lastKind(self: &Self) -> ValueKindReturns the kind of the last complete value read.
Operation mark#
effect fn mark(self: &mut Self) -> usize
! OutOfMemoryError
? &mut AllocatorRemembers the open objects and lists and the scanner's position.
Operation recover#
effect fn recover(self: &mut Self, mark: usize, skip: bool) -> ()
! Issue | OutOfMemoryError
? &mut AllocatorReturns to the mark, closing the objects and lists opened since, and reads past the value
there when skip is true.
Operation release#
fn release(self: &mut Self, mark: usize) -> ()Forgets the mark and every later one.
Operation boolean#
effect fn boolean(self: &mut Self) -> bool
! Issue | OutOfMemoryError
? &mut AllocatorReads true or false.
Operation signed#
effect fn signed(self: &mut Self) -> i64
! Issue | OutOfMemoryError
? &mut AllocatorReads a JSON number as an i64.
Operation unsigned#
effect fn unsigned(self: &mut Self) -> u64
! Issue | OutOfMemoryError
? &mut AllocatorReads a JSON number as a u64.
Operation float#
effect fn float(self: &mut Self) -> f64
! Issue | OutOfMemoryError
? &mut AllocatorReads a JSON number as an f64.
Operation text#
effect fn text(self: &mut Self) -> String
! Issue | OutOfMemoryError
? &mut AllocatorReads a JSON string, with its escapes decoded.
Operation null#
effect fn null(self: &mut Self) -> bool
! Issue | OutOfMemoryError
? &mut AllocatorReads past null and returns true, or returns false for another value.
Operation beginList#
effect fn beginList(self: &mut Self) -> ()
! Issue | OutOfMemoryError
? &mut AllocatorReads past [.
Operation nextElement#
effect fn nextElement(self: &mut Self) -> bool
! Issue | OutOfMemoryError
? &mut AllocatorReturns true at the next element, or reads past ] and returns false.
Operation beginObject#
effect fn beginObject(self: &mut Self) -> ()
! Issue | OutOfMemoryError
? &mut AllocatorReads the object's members into an index once, so member finds each without scanning.
Operation member#
effect fn member(self: &mut Self, key: string) -> bool
! Issue | OutOfMemoryError
? &mut AllocatorFinds 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#
effect fn nextMember(self: &mut Self) -> Option<String>
! Issue | OutOfMemoryError
? &mut AllocatorOperation rejectUnread#
effect fn rejectUnread(self: &mut Self, expected: string<'static>) -> ()
! Issue | OutOfMemoryError
? &mut AllocatorReports every member no member call found, at its key.
Operation endObject#
effect fn endObject(self: &mut Self) -> ()
! Issue | OutOfMemoryError
? &mut AllocatorJumps past the whole object being read.
JsonSchemaWriter#
pub struct JsonSchemaWriterA 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#
impl JsonSchemaWriterAssociated function make#
pub fn make() -> JsonSchemaWriterReturns a writer for one top-level value.
Implementation SchemaWriter for JsonSchemaWriter#
impl SchemaWriter for JsonSchemaWriterOperation taggedOptions#
fn taggedOptions(self: &Self) -> boolOperation boolean#
effect fn boolean(self: &mut Self, value: bool) -> ()
! Issue | WriterError
? &mut WriterWrites true or false.
Operation signed#
effect fn signed(self: &mut Self, value: i64) -> ()
! Issue | WriterError
? &mut WriterWrites the integer in decimal.
Operation unsigned#
effect fn unsigned(self: &mut Self, value: u64) -> ()
! Issue | WriterError
? &mut WriterWrites the integer in decimal.
Operation float#
effect fn float(self: &mut Self, value: f64) -> ()
! Issue | WriterError
? &mut WriterWrites the number. A NaN or an infinity fails with IssueReason.InvalidValue.
Operation text#
effect fn text(self: &mut Self, value: string) -> ()
! Issue | WriterError
? &mut WriterWrites a JSON string, with the escapes JSON needs.
Operation null#
effect fn null(self: &mut Self) -> ()
! Issue | WriterError
? &mut WriterWrites null.
Operation beginList#
effect fn beginList(self: &mut Self, count: usize) -> ()
! Issue | WriterError
? &mut WriterWrites [. JSON does not write count.
Operation element#
effect fn element(self: &mut Self) -> ()
! Issue | WriterError
? &mut WriterWrites , before every element but the first.
Operation endList#
effect fn endList(self: &mut Self) -> ()
! Issue | WriterError
? &mut WriterWrites ].
Operation beginObject#
effect fn beginObject(self: &mut Self, count: usize) -> ()
! Issue | WriterError
? &mut WriterWrites {. JSON does not write count.
Operation key#
effect fn key(self: &mut Self, name: string) -> ()
! Issue | WriterError
? &mut WriterWrites , before every member but the first, then the key and :.
Operation endObject#
effect fn endObject(self: &mut Self) -> ()
! Issue | WriterError
? &mut WriterWrites }.
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.