Home / Docs / Standard library / Prelude

JsonError

Release v0.4.0Edition 0.2 and later

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

una
pub kind JsonError = Syntax(at: Int) | TooDeep(at: Int) | DuplicateKey(at: Int) | NumberTooLong(at: Int)

Why a text is not one JSON value, at the first error in reading order (spec/23 §3).

Variants

See also

parse_json

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.