Skip to content
Draft

json

The json module provides JSON parsing and serialization.

import json
import { parse, stringify } from json

Parse a JSON string:

@json_string = '{"name": "Alice", "age": 30}'
@data = @json#parse(@json_string)

Parse JSON from a file:

@data = @json#parse_file("config.json")

Parse into a typed record:

record User
name: String
age: Int
fin record.
@json_string = '{"name": "Alice", "age": 30}'
@user = @json#parse_typed<User>(@json_string)

Convert value to JSON string:

@data = {"name": "Alice", "age": 30}
@json_string = @json#stringify(@data)
@// '{"name":"Alice","age":30}'

Pretty-print JSON:

@json_string = @json#stringify_pretty(@data, 2)

Output:

{
"name": "Alice",
"age": 30
}

Write JSON to file:

@json#to_file("output.json", @data)

Write pretty JSON to file:

@json#to_file_pretty("output.json", @data, 2)
@json#Null @// null
@json#Bool(true) @// true
@json#Int(42) @// 42
@json#Float(3.14) @// 3.14
@json#String("hello") @// "hello"
@json#Array([1, 2, 3]) @// [1,2,3]
@json#Object({"key": "value"}) @// {"key":"value"}

Check if string is valid JSON:

@json#is_valid('{"key": "value"}') @// true
@json#is_valid('invalid') @// false

Validate JSON against schema:

@schema = '{
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"}
},
"required": ["name", "age"]
}'
@result = @json#validate(@json_string, @schema)

Get value at JSON path:

@data = @json#parse('{"users": [{"name": "Alice"}, {"name": "Bob"}]}')
@name = @json#get_at(@data, "users[0].name") @// "Alice"

Set value at JSON path:

@json#set_at(@data, "users[0].name", "Charlie")

Delete value at JSON path:

@json#delete_at(@data, "users[1]")

Merge two JSON objects:

@a = {"name": "Alice"}
@b = {"age": 30}
@merged = @json#merge(@a, @b)
@// {"name": "Alice", "age": 30}

Compute difference between JSON values:

@changes = @json#diff(@old, @new)

Apply JSON patch:

@patched = @json#patch(@original, @patch)

Resolve JSON Pointer:

@value = @json#resolve(@data, "/users/0/name")

Parse large JSON incrementally:

@parser = @json#Parser::new("huge_file.json")
for @event in @parser
match @event
when StartObject then write("Object started")
when Key then write("Key: " + @event#value)
when Value then write("Value: " + @event#value)
when EndObject then write("Object ended")
fin match.
fin for.
@result = @json#parse(@invalid_json)
match @result
when ok then write("Parsed: " + string(@result#value))
when err then write("Parse error: " + @result#error)
fin match.
record User
name: String
age: Int
email: String?
fin record.
@json_string = '{"name": "Alice", "age": 30, "email": "alice@example.com"}'
@user = @json#from_json<User>(@json_string)
@json_output = @json#to_json(@user)

Generate JSON Schema from record type:

@schema = @json#schema_for<User>()
@compact = @json#compact(@data)
@pretty = @json#pretty(@data, 2)