Zig
Zig
JSON: Nested Objects
See more JSON Examples
Here we have a JSON object that contains nested JSON objects. This example demonstrates how to access the contents of the nested objects.
{
"name": "donut",
"image":
{
"fname": "donut.jpg",
"w": 200,
"h": 200
},
"thumbnail":
{
"fname": "donutThumb.jpg",
"w": 32,
"h": 32
}
}
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 = "{\"name\": \"donut\",\"image\":{\"fname\": \"donut.jpg\",\"w\": 200,\"h\": 200},\"thumbnail\":{\"fname\": \"donutThumb.jpg\",\"w\": 32,\"h\": 32}}";
json.load(json_str) catch {
std.debug.print("{s}\n", .{try json.getLastErrorText(alloc)});
return;
};
// Get the "image" object.
const image_obj = try chilkat.JsonObject.init();
defer image_obj.deinit();
json.objectOf2("image", image_obj) catch {};
std.debug.print("image: fname={s}, width={d}, height={d}\n", .{ try image_obj.stringOf(alloc, "fname"), image_obj.intOf("w"), image_obj.intOf("h") });
// Get the "thumbnail" object.
const thumb_obj = try chilkat.JsonObject.init();
defer thumb_obj.deinit();
json.objectOf2("thumbnail", thumb_obj) catch {};
std.debug.print("thumbnail: fname={s}, width={d}, height={d}\n", .{ try thumb_obj.stringOf(alloc, "fname"), thumb_obj.intOf("w"), thumb_obj.intOf("h") });
}