Home / Docs / Standard library / Prelude

to_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 to_json(j: Json) -> Text

The canonical JSON text of j (spec/23 §4).

Parameters

Returns

Text: the canonical JSON text of j, with no white space: Null as null, a Boolean as true or false, a Number in decimal, a Decimal as its text, a Str as quote_json writes it, and an object's entries in key order; parsing it gives j back when its arrays and objects nest at most 512 deep and each Number has at most 4300 digits, since parse_json refuses a deeper value with TooDeep and a longer integer with NumberTooLong; the result carries the labels of j (spec/23 §5).

See also

parse_json, quote_json

Cost

Time O(n) time for an output of n scalar values, except that writing a Number of d digits takes O(d²) (spec/23 §6), where:

Example

src/shop.unauna
module shop

--- An item written as JSON, its keys in order.
pub main() -> Unit
  uses @console: Console[print]
=
  let fields = empty_map().with(key: "price", value: Number(1999)).with(key: "name", value: Str("Desk lamp"))
  let text = Object(fields).to_json()
  @console.print(text)

una run . prints:

Output
{"name":"Desk lamp","price":1999}

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.