Zig
Zig
JSON Iterate Members
See more JSON Examples
Demonstrates how to loop over the immediate members of a JSON object.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 = "{ \"id\": 1, \"name\": \"A green door\", \"tags\": [\"home\", \"green\"], \"price\": 125 }";
json.load(json_str) catch {
std.debug.print("{s}\n", .{try json.getLastErrorText(alloc)});
return;
};
const num_members = json.getSize();
var i: i32 = 0;
i = 0;
while (i < num_members) : (i += 1) {
const name = try json.nameAt(alloc, i);
const value = try json.stringAt(alloc, i);
std.debug.print("{s}: {s}\n", .{ name, value });
const i_value = json.intAt(i);
std.debug.print("{s} as integer: {d}\n", .{ name, i_value });
}
// Note: The StringAt method returns the value as a string regardless of the type.
// If the value is a JSON array (such as for ["home", "green"]), then the JSON encoding
// of the entire array is returned.
// The IntAt method returns the value as an integer. If the value does not convert to
// an integer, then 0 is returned.
}