Sample code for 30+ languages & platforms
Zig

JSON: Array of Objects

See more JSON Examples

Here we have a JSON object that contains an array, where each element in the array is a JSON object. This example demonstrates how to access the objects contained within an array.
{ 
  "employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter","lastName":"Jones"}
  ]
}

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 json = try chilkat.JsonObject.init();
    defer json.deinit();

    // This is the above JSON with whitespace chars removed (SPACE, TAB, CR, and LF chars).
    // The presence of whitespace chars for pretty-printing makes no difference to the Load
    // method.
    const json_str = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"},{\"firstName\":\"Anna\", \"lastName\":\"Smith\"},{\"firstName\":\"Peter\",\"lastName\":\"Jones\"}]}";

    json.load(json_str) catch {
        std.debug.print("{s}\n", .{try json.getLastErrorText(alloc)});
        return;
    };

    // Get the "employees" array.
    const employees = json.arrayOf("employees") catch {
        std.debug.print("employees member not found.\n", .{});
        return;
    };
    defer employees.deinit();

    // Iterate over each employee, getting the JSON object at each index.
    const num_employees = employees.getSize();
    var i: i32 = 0;
    while (i < num_employees) {
        const emp_obj = try employees.objectAt(i);
        defer emp_obj.deinit();

        std.debug.print("employee[{d}] = {s} {s}\n", .{ i, try emp_obj.stringOf(alloc, "firstName"), try emp_obj.stringOf(alloc, "lastName") });

        i = i + 1;
    }
}