json
The json module provides functions to encode and decode data in JSON format. It is written in Koji: std/json.kj.
The Json Type
JSON data is represented by a sum type, so every kind of value is explicit and must be handled with match:
type Json = {
Null
Bool(value: boolean)
Int(value: int)
Decimal(value: decimal)
String(value: string)
Array(items: Json[])
Object(fields: Map[string, Json])
}
- A number without
.,eorEis anInt(2025); any other number is aDecimal(2025.0,1e3), exactly as written (rounded only beyond 34 significant digits). - JSON
nullis theNullvariant: Koji itself has nonull. - An object is a
Map[string, Json](also namedjson.JsonObject), which keeps the order of its keys. Int(1) == Decimal(1.0)isfalse: they are different variants.
Functions
parse(text: string) -> Result[Json, JsonError]
Converts a JSON string into aJsonvalue.stringify(value: Json) -> string
Converts aJsonvalue to a JSON string. ADecimalis written in full and always with a decimal point (Decimal(3)is written3.0,Decimal(1e20)is written100000000000000000000.0), so that parsing the text back gives aDecimalagain.get(value: Json, key: string) -> Option[Json]
The fieldkeyof anObject, orNoneifvalueis not an object or has no such field.asString(value: Json) -> Option[string],asInt(value: Json) -> Option[int],asBool(value: Json) -> Option[boolean]
The payload of aString,IntorBool, orNonefor any other variant.asDecimal(value: Json) -> Option[decimal]
The payload of aDecimal, or of anIntconverted todecimal. Many serializers write3.0as3, so this accepts both.
Errors
type JsonError = {
Syntax(message: string, line: int, column: int)
NumberOutOfRange(text: string, line: int, column: int) // an integer too large for int
}
Example
import json
immut text: string = '{"name": "koji", "year": 2025}'
match (json.parse(text)) {
Ok(Object(fields)) => match (fields['name']) {
String(name) => print(name) // koji
_ => print('name is not a string')
}
Ok(_) => print('expected an object')
Err(error) => print(`invalid JSON: ${error}`)
}
With the helper functions:
import json
match (json.parse('{"name": "koji", "year": 2025}')) {
Ok(data) => {
match (json.get(data, 'year')) {
Some(year) => print(json.asInt(year)) // Some(2025)
None => print('no year')
}
print(json.stringify(data)) // {"name":"koji","year":2025}
}
Err(error) => print(error)
}
Building a value to convert:
import json
print(json.stringify(json.Array([json.Int(1), json.Decimal(2.0), json.Null]))) // [1,2.0,null]