JSON Parse
The std/json module provides a complete JSON parser and builder. JSON values are represented as tagged Array nodes — the first element is the type tag and the second is the value — making it easy to inspect and traverse any JSON document.
Code
// JSON con std/json: construir objetos, arrays y serializar/parsear números
import "std/json"
fn main() -> int {
// Construir un objeto JSON programáticamente
let keys: Array = ["name", "age", "activo"]
let vals: Array = []
vals.push(json_string("Alice"))
vals.push(json_number(30))
vals.push(json_bool(true))
let obj: Array = json_object(keys, vals)
let serializado: String = json_stringify(obj)
print("Objeto: " + serializado)
// Construir un array JSON
let items: Array = []
items.push(json_number(10))
items.push(json_number(20))
items.push(json_number(30))
let arr: Array = json_array(items)
print("Array: " + json_stringify(arr))
// Parsear un número
let parsed: Array = json_parse("42")
print("Tipo: " + json_type(parsed))
let val: int = parsed[1]
print("Valor: " + int_to_string(val))
// Parsear un array de números
let parsed2: Array = json_parse("[1,2,3]")
print("Array parseado: " + json_stringify(parsed2))
return 0
}
Output
Objeto: {"name":"Alice","age":30,"activo":true}
Array: [10,20,30]
Tipo: number
Valor: 42
Array parseado: [1,2,3]
Explanation
JSON values are constructed with typed builder functions: json_string, json_number, json_bool, json_object, and json_array. Each returns a tagged Array where node[0] is the type string (e.g. "number") and node[1] is the payload. This uniform representation makes recursive traversal straightforward.
json_stringify serializes any JSON node back to a compact string. json_parse does the reverse — it accepts a JSON string and returns the same tagged-array structure, which you can then inspect with json_type or index directly.
For reading nested fields, you would chain array indexing: obj[1][1] reaches the first value in a JSON object node. The next example (16) focuses on building complex nested structures for serialization.