JSON
Release v0.4.0
parse_json, to_json and quote_json read and write JSON (spec/23, edition 0.2).
- The value is the prelude kind
Json:Null,Boolean(value),Number(value: Int)for an exact integer,Decimal(text)for any other number as written,Str(value),Array(items: List[Json])andObject(fields: Map[Text, Json]), whose keys are in ascending order. - Parsing.
t.parse_json()fails withJsonError:Syntax(at),TooDeep(at)past 512 levels,DuplicateKey(at), orNumberTooLong(at)for an integer over 4300 digits.atcounts scalar values. Handle it withif error, orattemptfor theResult. - Writing.
j.to_json()writes the canonical compact form, keys in order.t.quote_json()writes one JSON string, for building JSON text by interpolation. - Decimals. A
Decimalholds aJsonNumber, a number with a fraction or an exponent, which parsing makes, orchecked(t, is_json_number(it)). - Labels. A value parsed from a labeled text, its fields, and whether and where the parse failed, all carry the text's labels. In edition 0.4 a constructor takes labeled data and its result carries their join:
Str(value: token)with asecrettoken is asecret Json, itsto_json()asecret Text, and every value awhenbinds from it issecret; it is U4001 or U4003 only where it reaches a lower declared type or a sink. In editions 0.2 and 0.3 asecretcannot enter aJsonconstructor (U4001): build the text withquote_jsonand interpolation instead, and its result issecret. - Cost. Parsing is O(n + Σ k log k), and O(n) when keys arrive in order. Writing is O(n). Neither recurses on depth.
- Parse, then branch. After
attempton a labeled text, the branches ofwhen rrun under the text's label, so a call that can fail inside them is U4002. Give the parse a default withif error use, then branch on the value, and make fallible calls outside the branches:
una
module config
--- The port of a configuration, or 8080 when it is missing or not a number.
pub port(text: internal Text) -> internal Int
=
let doc = text.parse_json()
if error use Null
when doc
is Object(fields) ->
let value = fields.get(key: "port")
if none use Null
when value
is Number(n) -> n
else -> 8080
else -> 8080
--- The configuration written back, with the port replaced.
pub with_port(fields: Map[Text, Json], port: Int) -> Text = Object(fields.with(key: "port", value: Number(port))).to_json()