Nyx by Example

JSON Serialize

This example builds on the JSON foundations from the previous page to show how real-world data — a list of people — is serialized into a nested JSON response. A helper function encapsulates the per-record construction, keeping main clean and readable.

Code

// Serializar datos a JSON con std/json: json_object, json_array, json_stringify

import "std/json"

fn build_persona(nombre: String, edad: int, activo: bool) -> Array {
    let keys: Array = ["nombre", "edad", "activo"]
    let vals: Array = []
    vals.push(json_string(nombre))
    vals.push(json_number(edad))
    vals.push(json_bool(activo))
    return json_object(keys, vals)
}

fn main() -> int {
    // Objeto simple
    let persona: Array = build_persona("Bob", 25, true)
    print(json_stringify(persona))

    // Array de objetos
    let lista: Array = []
    lista.push(build_persona("Ana", 30, true))
    lista.push(build_persona("Carlos", 40, false))
    lista.push(build_persona("Dina", 22, true))

    let arr: Array = json_array(lista)
    print(json_stringify(arr))

    // Objeto anidado
    let meta_keys: Array = ["version", "total"]
    let meta_vals: Array = []
    meta_vals.push(json_number(1))
    meta_vals.push(json_number(3))
    let meta: Array = json_object(meta_keys, meta_vals)

    let resp_keys: Array = ["meta", "data"]
    let resp_vals: Array = []
    resp_vals.push(meta)
    resp_vals.push(arr)
    let resp: Array = json_object(resp_keys, resp_vals)

    print(json_stringify(resp))

    return 0
}

Output

{"nombre":"Bob","edad":25,"activo":true}
[{"nombre":"Ana","edad":30,"activo":true},{"nombre":"Carlos","edad":40,"activo":false},{"nombre":"Dina","edad":22,"activo":true}]
{"meta":{"version":1,"total":3},"data":[{"nombre":"Ana","edad":30,"activo":true},{"nombre":"Carlos","edad":40,"activo":false},{"nombre":"Dina","edad":22,"activo":true}]}

Explanation

build_persona is a plain Nyx function that takes typed arguments and returns a JSON object node. Wrapping construction logic in a function prevents key/value array mismatches and makes the code self-documenting — the function signature tells you exactly what fields each record contains.

Arrays of objects are built by pushing individual object nodes into a plain Array and wrapping the result with json_array. Because JSON nodes are just tagged arrays, they compose naturally: you can push an object node as the value of another object's field to create arbitrarily deep nesting.

The final resp object wraps meta and data into a single API-style response envelope. This pattern — a metadata object plus a data array — is common in REST APIs and shows how std/json handles real production shapes without any special-case syntax.

← Previous Next →

Source: examples/by-example/16-json-serialize.nx