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#
JsonErrorfor invalid JSON, duplicate keys, nesting deeper thanMAX_DEPTH(64), or trailing content.Json.parsealso rejects numbers outside finitef64;Json.parseExactdoes not.OutOfMemoryErrorif theAllocatorcannot supply the tree.WriterErrorfrom the write functions if theWriterfails.
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#
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#
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#
pub struct JsonEntryOne key and value of a JSON object.
Field key#
pub key: StringThe key, with escapes decoded.
Field value#
pub value: ValueThe value.
JsonNumber#
pub union JsonNumberAn 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#
IntegerAn integer that fits in i64.
Field value#
pub value: i64The value.
Unsigned#
UnsignedAn integer more than i64.MAX that fits in u64.
Field value#
pub value: u64The value.
Float#
FloatA number with a fraction or an exponent, or an integer too large for u64.
Field value#
pub value: f64The nearest f64.
Decimal#
DecimalAn exact decimal number retained without a precision or exponent bound by Json.parseExact.
Field text#
pub text: StringA validated JSON number spelling. Manually constructed values must obey JSON number syntax.
JsonNumberView#
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#
IntegerA signed machine integer.
Field value#
pub value: i64The exact integer value.
Unsigned#
UnsignedAn unsigned machine integer.
Field value#
pub value: u64The exact integer value.
Float#
FloatA binary floating-point value.
Field value#
pub value: f64The stored f64; manually constructed trees can contain nonfinite values.
Decimal#
DecimalA validated JSON decimal spelling with no precision or exponent bound.
Field text#
pub text: string<'text>The number text, borrowed from the tree or document.
Implementation Copy for JsonNumberView<'text>#
impl<'text> Copy for JsonNumberView<'text>Implementation JsonNumber#
impl JsonNumberMethod view#
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>#
impl<'text> JsonNumberView<'text>Method toOwned#
pub effect fn toOwned(self: Self) -> JsonNumber ! OutOfMemoryError ? &mut AllocatorCopies a number into independently owned storage. Machine-number variants do not allocate.
Errors#
OutOfMemoryErrorif decimal text cannot be copied.
Value#
pub union ValueOne 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#
NullJSON null.
Bool#
BoolJSON true or false.
Field value#
pub value: boolThe boolean value.
Number#
NumberA JSON number.
Field value#
pub value: JsonNumberThe number, as a machine value or an owned exact decimal spelling.
String#
StringA JSON string.
Field text#
pub text: StringThe text, with escapes decoded.
Array#
ArrayA JSON array.
Field values#
pub values: List<Value>The elements in source order.
Object#
ObjectA JSON object.
Field entries#
pub entries: List<JsonEntry>The members in source order.
Json#
pub struct JsonThe owner type of the JSON parse, write, and read operations. It has no fields and is never constructed.
Implementation Json#
impl JsonAssociated function copy#
pub effect fn copy(value: &Value) -> Value ! OutOfMemoryError ? &mut AllocatorCopies a tree into independent owned storage, preserving object order and exact number text.
Errors#
OutOfMemoryErrorif the allocator cannot supply the copied tree.
Associated function parse#
pub effect fn parse(bytes: &[u8]) -> Value ! JsonError | OutOfMemoryError ? &mut AllocatorParses 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#
JsonErrorifbytesis 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.OutOfMemoryErrorif theAllocatorcannot supply the tree.
Associated function parseExact#
pub effect fn parseExact(bytes: &[u8]) -> Value ! JsonError | OutOfMemoryError ? &mut AllocatorParses 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#
JsonErrorfor invalid JSON, duplicate decoded keys, excessive nesting, or trailing content.OutOfMemoryErrorif the allocator cannot supply the owned tree and number text.
Associated function decode#
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#
JsonErrorif the JSON is not valid, the value does not have typeT(TypeMismatch), a number does not fit (NumberOutOfRange), or content follows the value (TrailingContent).
Associated function deserialize#
pub effect fn deserialize<T: Deserialize>(bytes: &[u8])
-> T ! JsonError | OutOfMemoryError ? &mut AllocatorReads bytes as one complete JSON document of type T.
Errors#
JsonErrorif the JSON is not valid, the value does not have typeT, or content follows the value.OutOfMemoryErrorif theAllocatorcannot supply the value.
Associated function serialize#
pub effect fn serialize<T: Serialize>(value: &T, options: &JsonOptions)
-> () ! JsonError | WriterError ? &mut WriterWrites value as JSON to the Writer, with options.
Errors#
JsonErrorif the nesting is deeper than the limit inoptions, or a float is not finite.WriterErrorif theWriterfails. Bytes that it accepted before the failure stay written.
Examples#
Write a struct#
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#
pub effect fn write(document: &Value) -> () ! JsonError | WriterError ? &mut WriterWrites document as compact JSON to the Writer. It does not flush the Writer.
Errors#
JsonErrorif the nesting is deeper than 64.WriterErrorif theWriterfails.
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#
pub effect fn writeWith(document: &Value, options: &JsonOptions)
-> () ! JsonError | WriterError ? &mut WriterWrites document as JSON to the Writer, with the indentation and depth limit of options.
It does not flush the Writer.
Errors#
JsonErrorif the nesting is deeper than the limit inoptions.WriterErrorif theWriterfails.
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#
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#
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#
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#
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#
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#
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#
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#
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#
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#
pub fn equal(left: &Value, right: &Value) -> boolCompares 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#
pub fn numberIsFinite(value: &JsonNumber) -> boolReturns 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#
pub fn compareNumbers(left: &JsonNumber, right: &JsonNumber) -> i32Returns -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#
pub fn isIntegerNumber(value: &JsonNumber) -> boolReturns 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#
pub effect fn multipleOfNumbers(value: &JsonNumber, divisor: &JsonNumber) -> bool
! OutOfMemoryError ? &mut AllocatorReturns 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#
OutOfMemoryErrorif decimal arithmetic scratch storage cannot be allocated.
Gotchas#
Traps for a NaN or infinite machine-number argument.
Associated function asUsizeNumber#
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#
impl Serialize for ValueOperation serialize#
effect fn serialize(self: &Self, options: &JsonOptions)
-> () ! JsonError | WriterError ? &mut WriterImplementation Deserialize for Value#
impl Deserialize for ValueOperation deserialize#
effect fn deserialize(scanner: &mut JsonScanner<'_>)
-> Self ! JsonError | OutOfMemoryError ? &mut AllocatorJsonDocument#
pub struct JsonDocumentA 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#
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#
pub struct JsonNodeOne value in a JsonDocument: its position in the document.
Implementation Copy for JsonNode#
impl Copy for JsonNodeJsonKind#
pub enum JsonKindThe kind of a value in a JsonDocument.
Null#
NullJSON null.
Bool#
BoolJSON true or false.
Number#
NumberA JSON number.
String#
StringA JSON string.
Array#
ArrayA JSON array.
Object#
ObjectA JSON object.
JsonMember#
pub struct JsonMemberOne member of an object in a JsonDocument: the node of its key, which is a string, and the
node of its value.
Field key#
pub key: JsonNodeThe key, a string node.
Field value#
pub value: JsonNodeThe value.
Implementation Copy for JsonMember#
impl Copy for JsonMemberJsonItems#
pub struct JsonItemsThe elements of an array in a JsonDocument, in source order. JsonDocument.items makes it.
JsonMembers#
pub struct JsonMembersThe members of an object in a JsonDocument, in source order. JsonDocument.members makes
it.
Implementation JsonItems#
impl JsonItemsMethod next#
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#
impl JsonMembersMethod next#
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#
impl JsonDocumentAssociated function parse#
pub effect fn parse(bytes: &[u8]) -> JsonDocument ! JsonError | OutOfMemoryError ? &mut AllocatorParses 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#
JsonErrorifbytesis not one valid JSON value, with the reason and offset thatJson.parsereports.OutOfMemoryErrorif theAllocatorcannot supply the buffers.
Associated function fromValue#
pub effect fn fromValue(value: &Value) -> JsonDocument ! OutOfMemoryError ? &mut AllocatorReturns a document that holds a copy of value.
Errors#
OutOfMemoryErrorif theAllocatorcannot supply the buffers.
Method root#
pub fn root(self: &Self) -> JsonNodeReturns the node of the whole document.
Method kind#
pub fn kind(self: &Self, node: JsonNode) -> JsonKindReturns the kind of node.
Method asBool#
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#
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#
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#
pub fn length(self: &Self, node: JsonNode) -> usizeReturns the number of elements of an array or members of an object, or 0 for any other value.
Method items#
pub fn items(self: &Self, node: JsonNode) -> JsonItemsReturns the elements of an array, or no elements if node is not an array.
Method members#
pub fn members(self: &Self, node: JsonNode) -> JsonMembersReturns the members of an object, or no members if node is not an object.
Method field#
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#
pub effect fn toValue(self: &Self, node: JsonNode) -> Value ! OutOfMemoryError ? &mut AllocatorReturns a Value tree that holds a copy of node and everything in it.
Errors#
OutOfMemoryErrorif theAllocatorcannot supply the tree.
Method write#
pub effect fn write(self: &Self) -> () ! JsonError | WriterError ? &mut WriterWrites the document as compact JSON to the Writer. It does not flush the Writer.
Errors#
JsonErrorwith reasonInvalidNumberfor a float that is not finite, which onlyJsonDocument.fromValuecan store.WriterErrorif theWriterfails.
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#
pub effect fn writeWith(self: &Self, options: &JsonOptions) -> () ! JsonError | WriterError ? &mut WriterWrites the document as JSON to the Writer, with the indentation and depth limit of
options. It does not flush the Writer.
Errors#
JsonErrorif the nesting is deeper than the limit inoptions, or with reasonInvalidNumberfor a float that is not finite.WriterErrorif theWriterfails.
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.