Zig
Zig
JSON: Nested Array
See more JSON Examples
Here we have a JSON object that contains nested arrays. This example demonstrates how to access the contents of the nested arrays.
{
"numbers" : [
["even", 2, 4, 6, 8],
["prime", 2, 3, 5, 7, 11, 13]
] }
Chilkat Zig Downloads
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 = "{ \"numbers\" : [ [\"even\", 2, 4, 6, 8], [\"prime\", 2, 3, 5, 7, 11, 13] ] }";
json.load(json_str) catch {
std.debug.print("{s}\n", .{try json.getLastErrorText(alloc)});
return;
};
// Get the value of the "numbers" object, which is an array that contains JSON arrays.
const outer_array = json.arrayOf("numbers") catch {
std.debug.print("numbers array not found.\n", .{});
return;
};
defer outer_array.deinit();
const num_arrays = outer_array.getSize();
var i: i32 = 0;
i = 0;
while (i < num_arrays) : (i += 1) {
const inner_array = try outer_array.arrayAt(i);
defer inner_array.deinit();
// The first item in the innerArray is a string
std.debug.print("{s}:\n", .{try inner_array.stringAt(alloc, 0)});
const num_inner_items = inner_array.getSize();
var j: i32 = 0;
j = 1;
while (j < num_inner_items) : (j += 1) {
std.debug.print(" {d}\n", .{inner_array.intAt(j)});
}
}
}