Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.1.0+

Create a JSON Array of Objects

See more JSON Examples

Demonstrates how to create a JSON array of objects.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    const arr = try chilkat.JsonArray.init();
    defer arr.deinit();

    const obj = try chilkat.JsonObject.init();
    defer obj.deinit();

    // Create a new and empty JSON object in the 1st position of the JSON array
    // and return the reference in the last argument.
    arr.addObjectAt2(0, obj) catch {};
    obj.updateString("Name", "Otto") catch {};
    obj.updateInt("Age", 29) catch {};
    obj.updateBool("Married", false) catch {};

    // Create a new and empty JSON object in the 2nd position of the JSON array
    // and return the reference in the last argument.
    arr.addObjectAt2(1, obj) catch {};
    obj.updateString("Name", "Connor") catch {};
    obj.updateInt("Age", 43) catch {};
    obj.updateBool("Married", true) catch {};

    // Create a new and empty JSON object in the 3rd position of the JSON array
    // and return the reference in the last argument.
    arr.addObjectAt2(2, obj) catch {};
    obj.updateString("Name", "Ramona") catch {};
    obj.updateInt("Age", 34) catch {};
    obj.updateBool("Married", true) catch {};

    // Examine what we have:
    arr.setEmitCompact(false);
    std.debug.print("{s}\n", .{try arr.emit(alloc)});

    // The output is:

    // [
    //   {
    //     "Name": "Otto",
    //     "Age": 29,
    //     "Married": false
    //   },
    //   {
    //     "Name": "Connor",
    //     "Age": 43,
    //     "Married": true
    //   },
    //   {
    //     "Name": "Ramona",
    //     "Age": 34,
    //     "Married": true
    //   }
    // ]
}