---
title: "JSON"
url: https://una-lang.org/en/docs/guides/json/
release: v0.4.0
source: https://github.com/una-lang/una/blob/v0.4.0/docs/guide/una-for-agents.md
---

# JSON

`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])` and `Object(fields: Map[Text, Json])`, whose keys are in ascending order.
- **Parsing.** `t.parse_json()` fails with `JsonError`: `Syntax(at)`, `TooDeep(at)` past 512 levels, `DuplicateKey(at)`, or `NumberTooLong(at)` for an integer over 4300 digits. `at` counts scalar values. Handle it with `if error`, or `attempt` for the `Result`.
- **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 `Decimal` holds a `JsonNumber`, a number with a fraction or an exponent, which parsing makes, or `checked(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 a `secret` token is a `secret Json`, its `to_json()` a `secret Text`, and every value a `when` binds from it is `secret`; it is U4001 or U4003 only where it reaches a lower declared type or a sink. In editions 0.2 and 0.3 a `secret` cannot enter a `Json` constructor (U4001): build the text with `quote_json` and interpolation instead, and its result is `secret`.
- **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 `attempt` on a labeled text, the branches of `when r` run under the text's label, so a call that can fail inside them is U4002. Give the parse a default with `if 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()
```
