Zig Requires Chilkat v11.0.0+
Zig
Get the Root of a JSON Document
See more JSON Examples
Demonstrates how to get back to the JSON root object from anywhere in the JSON document. This example uses the following JSON document:
{
"flower": "tulip",
"abc":
{
"x": [
{ "a" : 1 },
{ "b1" : 100, "b2" : 200 },
{ "c" : 3 }
],
"y": 200,
"z": 200
}
}
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();
const json_str = "{\"flower\": \"tulip\",\"abc\":{\"x\": [{ \"a\" : 1 },{ \"b1\" : 100, \"b2\" : 200 },{ \"c\" : 3 }],\"y\": 200,\"z\": 200}}";
json.load(json_str) catch {
std.debug.print("{s}\n", .{try json.getLastErrorText(alloc)});
return;
};
// Get the "abc" object.
const abc_obj = try chilkat.JsonObject.init();
defer abc_obj.deinit();
json.objectOf2("abc", abc_obj) catch {
std.debug.print("{s}\n", .{try json.getLastErrorText(alloc)});
return;
};
// Side note: The JSON of a sub-part of the document can be emitted from any JSON object:
abc_obj.setEmitCompact(false);
std.debug.print("{s}\n", .{try abc_obj.emit(alloc)});
// Navigate to the "x" array
const x_array = try chilkat.JsonArray.init();
defer x_array.deinit();
abc_obj.arrayOf2("x", x_array) catch {};
// Navigate to the 2nd object contained within the array. This contains members b1 and b2
const b_obj = try chilkat.JsonObject.init();
defer b_obj.deinit();
x_array.objectAt2(1, b_obj) catch {};
// Show that we're at "b1/b2".
// The value of "b1" should be "200"
std.debug.print("b2 = {d}\n", .{b_obj.intOf("b2")});
// Now go back to the JSON doc root:
const doc_root = try chilkat.JsonObject.init();
defer doc_root.deinit();
b_obj.getDocRoot2(doc_root) catch {};
// We'll skip the null check and assume it's non-null...
// Pretty-print the JSON doc from the root to show that this is indeed the root.
doc_root.setEmitCompact(false);
std.debug.print("{s}\n", .{try doc_root.emit(alloc)});
}