Home / Docs / Standard library / Prelude
parse_json
A function of the prelude, in scope in every module. Edition 0.2 and later.
pub parse_json(t: Text) -> Json
fails JsonErrorThe one JSON value of t (spec/23 §3).
Parameters
t: the text
Returns
Json: the one JSON value that t writes, with optional white space (U+0020, U+0009, U+000A and U+000D) before and after it and nothing else; there is no limit on its size beyond the memory budget, and a run over it ends with U6003 at the call; when t is not one value, the failure is the first error in reading order; the result and the failure carry the labels of t (spec/23 §5), so with a labeled t, if error pass and if error fail are U4002, and attempt or if error use handles the failure.
Fails with
Syntaxwhentis not one JSON value of RFC 8259: there are no comments, trailing commas,NaN,Infinity, single quotes or byte order mark, no leading+or leading zero in a number, and no lone surrogate, raw scalar value below U+0020 or unknown escape in a string;atis the scalar position, from 0, of the first scalar value where no JSON text can continue, or the length oftwhen it ends earlyTooDeepwhen arrays and objects nest more than 512 deep;atis the scalar position, from 0, of the bracket that opens the 513th levelDuplicateKeywhen an object has two equal keys, compared after unescaping;atis the scalar position, from 0, of the second oneNumberTooLongwhen an integer has more than 4300 digits;atis the scalar position, from 0, of its first character; a number with a fraction or an exponent has no such limit
See also
Cost
Time O(n + Σ k log k) (spec/23 §6), where:
n: the length oftin scalar valuesk: the number of keys of one object;Σsumsk log kover the objects oft
Example
module shop
--- An order read from JSON, and why a text is not one JSON value.
order(raw: Text) -> Text
=
let outcome = attempt parse_json(raw)
when outcome
is Ok(value) -> written(value)
is Err(failure) -> reason(failure)
written(value: Json) -> Text
=
let text = value.to_json()
"read {text}"
reason(failure: JsonError) -> Text
=
when failure
is Syntax(at) -> "not JSON at {at}"
is TooDeep(at) -> "nested too deep at {at}"
is DuplicateKey(at) -> "a key twice at {at}"
is NumberTooLong(at) -> "a number too long at {at}"
pub main() -> Unit
uses @console: Console[print]
=
@console.print(order("\{\"lamp\": 3, \"desk\": 1\}"))
@console.print(order("[1, 2,]"))
@console.print(order("\{\"lamp\": 3, \"lamp\": 4\}"))una run . prints:
read {"desk":1,"lamp":3}
not JSON at 6
a key twice at 12Specification
Generated from the standard modules of una v0.4.0 (docs/std/listing.json, which is not part of the specification). The specification governs: spec/14 §1.