Sample code for 30+ languages & platforms
Zig

JSON: Access Array Values

See more JSON Examples

Demonstrates how to access values in a JSON array.

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();

    const json_str = "{ \"id\": 1, \"name\": \"A green door\", \"tags\": [\"home\", 22, \"green\"], \"price\": 125 }";

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

    // Get the "tags" array, which contains "home", 22, "green"
    const tags_array = json.arrayOf("tags") catch {
        std.debug.print("tags member not found.\n", .{});
        return;
    };
    defer tags_array.deinit();

    // Get the value at each array index.
    // Output will be:
    // [0] = home
    // [0] as integer = 0
    // [1] = 22
    // [1] as integer = 22
    // [2] = green
    // [2] as integer = 0

    const array_size = tags_array.getSize();
    var i: i32 = 0;
    i = 0;
    while (i < array_size) : (i += 1) {
        const s_value = try tags_array.stringAt(alloc, i);

        std.debug.print("[{d}] = {s}\n", .{ i, s_value });

        const i_value = tags_array.intAt(i);
        std.debug.print("[{d}] as integer = {d}\n", .{ i, i_value });
    }

    // Note: The StringAt method returns the value as a string regardless of the type.

    // The IntAt method returns the value as an integer.  If the value does not convert to
    // an integer, then 0 is returned.
}