Zig Requires Chilkat v11.0.0+
Zig
JSON: Miscellaneous Operations
See more JSON Examples
Demonstrates a variety of JSON API methods. This example uses the following JSON document:
{
"alphabet": "abcdefghijklmnopqrstuvwxyz",
"sampleData" : {
"pi": 3.14,
"apple": "juicy",
"hungry": true,
"withoutValue": null,
"answer": 42
}
}
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();
json.setEmitCompact(false);
// Assume the file contains the data as shown above..
json.loadFile("qa_data/json/sample2.json") catch {
std.debug.print("{s}\n", .{try json.getLastErrorText(alloc)});
return;
};
// Get the "sampleData" object:
const sample_data = try chilkat.JsonObject.init();
defer sample_data.deinit();
json.objectOf2("sampleData", sample_data) catch {};
// Demonstrate BoolAt and BoolOf
std.debug.print("hungry: {}\n", .{sample_data.boolOf("hungry")});
std.debug.print("hungry: {}\n", .{sample_data.boolAt(2)});
// StringOf returns the value as a string regardless of it's actual type:
std.debug.print("pi: {s}\n", .{try sample_data.stringOf(alloc, "pi")});
std.debug.print("answer: {s}\n", .{try sample_data.stringOf(alloc, "answer")});
std.debug.print("withoutValue: {s}\n", .{try sample_data.stringOf(alloc, "withoutValue")});
std.debug.print("hungry: {s}\n", .{try sample_data.stringOf(alloc, "hungry")});
// Demonstrate IsNullOf / IsNullAt
std.debug.print("withoutValue is null? {}\n", .{sample_data.isNullOf("withoutValue")});
std.debug.print("withoutValue is null? {}\n", .{sample_data.isNullAt(3)});
std.debug.print("apple is null? {}\n", .{sample_data.isNullOf("apple")});
std.debug.print("apple is null? {}\n", .{sample_data.isNullAt(1)});
// IntOf
std.debug.print("answer: {d}\n", .{sample_data.intOf("answer")});
// SetNullAt, SetNullOf
// Set "pi" to null
try sample_data.setNullAt(0);
// Set "answer" to null
try sample_data.setNullOf("answer");
// Show the changes:
std.debug.print("{s}\n", .{try json.emit(alloc)});
// Restore pi and apple:
try sample_data.setNumberAt(0, "3.14");
try sample_data.setNumberOf("answer", "42");
// Show the changes:
std.debug.print("{s}\n", .{try json.emit(alloc)});
// Add a null value named "afterApple" just after "apple"
try sample_data.addNullAt(2, "afterApple");
// Add a boolean value just after "pi"
try sample_data.addBoolAt(1, "afterPi", false);
// Examine the changes..
std.debug.print("{s}\n", .{try json.emit(alloc)});
}