Home / Docs / Standard library / Prelude

parse_json

Release v0.4.0Edition 0.2 and later

A function of the prelude, in scope in every module. Edition 0.2 and later.

una
pub parse_json(t: Text) -> Json
  fails JsonError

The one JSON value of t (spec/23 §3).

Parameters

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

See also

JsonError, to_json, Json

Cost

Time O(n + Σ k log k) (spec/23 §6), where:

Example

src/shop.unauna
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:

Output
read {"desk":1,"lamp":3}
not JSON at 6
a key twice at 12

Specification

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.