JSON

The json type holds one JSON value: an object, an array, a string, a number, a bool or null. It’s the only Luma type whose shape is known only when the program runs, which is exactly what JSON from a file or another program is like.

File config.json:

{
  "name": "Luma Notes",
  "port": 8080,
  "debug": false,
  "tags": ["notes", "tööd"],
  "server": {"host": "localhost"}
}
config: json = convert(file("config.json").read())
name: str = convert(config["name"])
port: int = convert(config["port"])
host: str = convert(config["server"]["host"])
tags: [str] = convert(config["tags"])
print("${name} on ${host}:${port}")
print(tags)

Output:

Luma Notes on localhost:8080
["notes", "tööd"]

Two rules make up the whole design:

  • Into json, anything goes, automatically. Numbers, strings, bools, lists and maps (with str keys) become JSON values wherever a json is expected. Dates and times become strings.
  • Out of json, use convert. The type you convert to says what you expect to find, and if the value isn’t that, convert raises error 11.

Reading JSON text

convert from a str to a json reads the text as JSON:

data: json = convert("{\"user\": \"Ann\", \"scores\": [90, 85]}")
print(data["user"])
print(data["scores"][1])
print(len(data["scores"]))

Output:

Ann
85
2

Text that isn’t valid JSON raises error 11, which says where the problem is:

err: error = nil
try err {
    bad: json = convert("{\"a\": 1,}")
}
print(err.message)

Output:

cannot convert to json: expected a key in quotes at line 1, column 9

Getting values out

json["key"] reads a key of an object, and json[0] a position in an array. Both give a json again, so they can be chained: config["server"]["host"]. A missing key is error 3 and a position outside the array is error 2, as with maps and lists. has(j, "key") checks for a key first.

To use a value, convert it to the type you expect:

item: json = convert("{\"id\": 7, \"price\": 2.5, \"tags\": [\"new\"], \"stock\": {\"shop\": 3}}")
id: int = convert(item["id"])
price: float = convert(item["price"])
tags: [str] = convert(item["tags"])
stock: {str: int} = convert(item["stock"])
print(id * 2)
print(price)
print(tags)
print(stock)

Output:

14
2.5
["new"]
{"shop": 3}
Converting a json toWorks for
int, byte, floata number (a float to int is cut off toward zero, as convert always does)
booltrue or false
stra string gives its text; anything else gives its JSON text
date, time, datetimea string with its text, like "2024-12-25" (see Dates and times)
[T]an array whose elements all convert to T
{str: T}an object whose values all convert to T
an obj typean object: its keys go into the fields of the same name
jsonanything: the same value
err: error = nil
item: json = convert("{\"id\": \"seven\"}")
try err {
    id: int = convert(item["id"])
}
print(err.message)

Output:

cannot convert a json string to an int

Looking inside

kind() tells what a value is: "object", "array", "string", "number", "bool" or "null". walk goes through an array with one variable, and through an object with two (each key and its value):

doc: json = convert("{\"a\": 1, \"b\": [true, null], \"c\": \"x\"}")
doc.walk(key, value) {
    print("${key} is a ${value.kind()}")
}
doc["b"].walk(v) {
    print(v.kind())
}

Output:

a is a number
b is a array
c is a string
bool
null

Walking an object as an array (or the other way around), or len of something that isn’t an array or object, raises error 11.

is checks for one kind, and tells an int from a float: is int, is float, is str, is bool, is null, is [json] (an array) and is {str: json} (an object). Where it says yes, convert to that type can’t fail:

data: json = convert("{\"age\": 30, \"height\": 1.8, \"tags\": [\"a\"]}")
if data["age"] is int {
    age: int = convert(data["age"])
    print(age + 1)
}
print(data["height"] is int)
print(data["tags"] is [json])

Output:

31
false
true

Building JSON

Where a json is expected, a literal can mix types freely, and null means JSON’s null:

user: json = {"name": "Ann", "age": 30, "tags": ["admin"], "boss": null}
user["age"] = 31
user["email"] = "ann@example.com"
user["tags"][] = "dev"
scores: [int] = [90, 85]
user["scores"] = scores
remove(user, "boss")
print(user)

Output:

{"name":"Ann","age":31,"tags":["admin","dev"],"email":"ann@example.com","scores":[90,85]}

Objects keep their keys in the order they were read or added.

A json put into another one is copied, so changing one doesn’t change the other, and no value can end up inside itself:

inner: json = {"n": 1}
outer: json = {"inner": inner}
inner["n"] = 2
print(outer)

Output:

{"inner":{"n":1}}

Assigning a json to another variable shares it, like a list: b: json = a and then b["x"] = 1 changes a too.

Writing JSON text

convert to a str gives compact JSON; pretty() gives it indented, for files people read:

order: json = {"id": 7, "items": [{"name": "tea", "count": 2}], "paid": true}
text: str = convert(order)
print(text)
print(order.pretty())

Output:

{"id":7,"items":[{"name":"tea","count":2}],"paid":true}
{
  "id": 7,
  "items": [
    {
      "name": "tea",
      "count": 2
    }
  ],
  "paid": true
}

print and "${...}" show a json the same way, as compact JSON, except that a JSON string shows its own text (without quotes).

Saving and loading is reading and writing text:

settings: json = {"theme": "dark", "size": 12}
file("settings.json").write(settings.pretty())
loaded: json = convert(file("settings.json").read())
size: int = convert(loaded["size"])
print(size + 1)

Output:

13

Details

  • Numbers: a number without a fraction or an exponent that fits an int is an int; any other number is a float. Floats are written as print shows them; nan and infinity become null, because JSON can’t hold them.
  • Strings: all of JSON’s escapes are read, including õ and surrogate pairs (😀 is 😀); a lone surrogate becomes U+FFFD. When writing, ", \ and control characters are escaped, and other text is written as it is (UTF-8).
  • A key written twice in JSON text keeps its first place, with the last value.
  • Nesting deeper than 1,000 levels is an error, in text and when building.
  • Comparing json values with == is a compile error: convert them first.

Your own types

A json object converts to and from an obj by field name: user: User = convert(data), and out: json = user. Keys the obj doesn’t have are ignored, and a missing key, or null, keeps the field’s default. An optional field (nick: ?str) is nil then, and nil becomes null.

Filling an object you have

convert makes a new object. fill(object, data) sets the fields of one that already exists, from a json or a str of JSON text: each key it has sets the field of that name, and every other field keeps its value. This is how a method fills its own object, self:

obj Device {
    status: str = "new"
    code: int = 0
    note: str = "kept"

    fn take(answer: str) {
        fill(self, answer)
    }
}

d: Device = Device {}
d.take("{\"status\": \"ERROR\", \"code\": 403, \"note\": null, \"other\": 1}")
print(d)

Output:

Device {status: "ERROR", code: 403, note: "kept"}
  • A key that is missing, or null, leaves its field as it is; keys no field has are ignored.
  • A field that is an obj is filled the same way, in place: the inner object stays the same object, and only its fields the JSON gives change. Lists and maps are replaced by the JSON’s.
  • A value that doesn’t fit raises error 11, naming the field: cannot fill code of a Device: cannot convert a json string to an int. The fields before it are already set.
  • self = convert(data) doesn’t work for this: it would only give the name self another object, while the caller’s variable keeps the old one; Luma doesn’t allow it, and says to use fill.

A schema from a type

schema(T) gives the JSON Schema of an obj type T, as a json. A JSON Schema describes what JSON must look like. AI models use it in two places: the input of a tool the model may call, and an answer it must give as JSON. The schema comes from the type’s fields, and the // comments become descriptions:

// A city's weather, as a tool's input.
obj Weather {
    city: str          // the city's name, e.g. Tartu
    days: int = 1      // how many days ahead
    units: ?str
}

s: json = schema(Weather)
print(s.pretty())

Output:

{
  "type": "object",
  "description": "A city's weather, as a tool's input.",
  "properties": {
    "city": {
      "type": "string",
      "description": "the city's name, e.g. Tartu"
    },
    "days": {
      "type": "integer",
      "description": "how many days ahead"
    },
    "units": {
      "type": [
        "string",
        "null"
      ]
    }
  },
  "required": [
    "city",
    "units"
  ],
  "additionalProperties": false
}

JSON that fits the schema converts into the type, so a model’s answer becomes an object with one convert:

// An invoice read from a document.
obj Invoice {
    number: str        // as printed on the invoice
    total: float
    lines: [Line]
}

obj Line {
    text: str
    amount: float
}

answer: str = "{\"number\": \"A-7\", \"total\": 12.5, \"lines\": [{\"text\": \"tea\", \"amount\": 12.5}]}"
data: json = convert(answer)
inv: Invoice = convert(data)
print(inv)

Output:

Invoice {number: "A-7", total: 12.5, lines: [Line {text: "tea", amount: 12.5}]}
Field typeSchema
int"integer"
byte"integer", 0 to 255
float"number"
str, file, folder"string"
bool"boolean"
date"string" with "format": "date": 2024-12-25
time, datetime"string" with "format": "time" or "date-time". A model may write a zone (2025-03-01T10:00:00Z); convert reads only text without one, and the claude mod puts such times on the local clock first
[T]"array" of T
{T} (a set)"array" of T with "uniqueItems": true
{str: T}"object" whose values are T
?TT or null
another obj typean "object" with its own fields
json{}: any JSON
  • Required: a field without a default is required; one with a default is not, because convert keeps the default when the key is missing. An optional field without a default (units: ?str) is required but may be null: strict tool use and structured outputs ask for every key, so the model says null instead of leaving it out.
  • No other keys: every object has "additionalProperties": false.
  • Descriptions: the comment on a field’s line, and the comment lines right above it, become its description. The comment right above the obj becomes the type’s. A blank line between a comment and the field means the comment isn’t about the field.
  • A type that contains itself (a Node with kids: [Node]) is described once, under $defs, and referred to with $ref. The type asked for is "#".
  • The argument is the name of an obj type: schema(Invoice), or schema(shop.Order) for a pub obj of an imported file. The schema is built when the program is compiled.
  • A field JSON can’t hold (a function, a buffer, a connection, a map with keys other than str) is a compile error that names the field.