Home / Docs / Standard library / Prelude

Json

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 Json = Null | Boolean(value: Bool) | Number(value: Int) | Decimal(text: JsonNumber) | Str(value: Text) | Array(items: List[Json]) | Object(fields: Map[Text, Json])

A JSON value (spec/23 §1). Number is an exact integer, a JSON number with neither a fraction nor an exponent; other numbers are Decimal, as written.

Variants

See also

parse_json, to_json, JsonNumber

Example

src/shop.unauna
module shop

--- What each value of an item's JSON is.
kind_of(value: Json) -> Text
=
  when value
    is Null -> "nothing"
    is Boolean(flag) -> "yes or no: {flag}"
    is Number(n) -> "a whole number: {n}"
    is Decimal(text) -> "a decimal: {text}"
    is Str(name) -> "a text: {name}"
    is Array(items) -> "a list of {items.len}"
    is Object(fields) -> "an object of {fields.len}"

price() -> Json
=
  parse_json("9.95")
    if error use Null

pub main() -> Unit
  uses @console: Console[print]
=
  @console.print(kind_of(Null))
  @console.print(kind_of(Boolean(true)))
  @console.print(kind_of(Number(12)))
  @console.print(kind_of(price()))
  @console.print(kind_of(Str("lamp")))
  @console.print(kind_of(Array([Number(1), Number(2)])))
  @console.print(kind_of(Object(empty_map().with(key: "desk", value: Number(1)))))

una run . prints:

Output
nothing
yes or no: true
a whole number: 12
a decimal: 9.95
a text: lamp
a list of 2
an object of 1

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.