Sample code for 30+ languages & platforms
Zig

Loading and Parsing a JSON Array

See more JSON Examples

A JSON array is JSON that begins with "[" and ends with "]". For example, this is a JSON array that contains 3 JSON objects.
[{"name":"jack"},{"name":"john"},{"name":"joe"}]
A JSON object, however, is JSON that begins with "{" and ends with "}". For example, this JSON is an object that contains an array.
{"pets":[{"name":"jack"},{"name":"john"},{"name":"joe"}]}
This example shows how loading a JSON array is different than loading a JSON object.

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 str_json_array = "[{\"name\":\"jack\"},{\"name\":\"john\"},{\"name\":\"joe\"}]";

    const str_json_object = "{\"pets\":[{\"name\":\"jack\"},{\"name\":\"john\"},{\"name\":\"joe\"}]}";

    // A JSON array must be loaded using JsonArray:
    const json_array = try chilkat.JsonArray.init();
    defer json_array.deinit();
    json_array.load(str_json_array) catch {};

    // Examine the values:
    var i: i32 = 0;
    while (i < json_array.getSize()) {
        const json_obj = try json_array.objectAt(i);
        defer json_obj.deinit();
        std.debug.print("{d}: {s}\n", .{ i, try json_obj.stringOf(alloc, "name") });

        i = i + 1;
    }

    // Output is:

    //     0: jack
    //     1: john
    //     2: joe

    // A JSON object must be loaded using JsonObject
    const json_object = try chilkat.JsonObject.init();
    defer json_object.deinit();
    json_object.load(str_json_object) catch {};

    // Examine the values:
    i = 0;
    const num_pets = json_object.sizeOfArray("pets");
    while (i < num_pets) {
        json_object.setI(i);
        std.debug.print("{d}: {s}\n", .{ i, try json_object.stringOf(alloc, "pets[i].name") });
        i = i + 1;
    }

    // Output is:

    //     0: jack
    //     1: john
    //     2: joe
}