Zig Requires Chilkat v11.0.0+
Zig
Sort JSON Object by Member Key Name
See more JSON Examples
Demonstrates how to sort the members of a JSON object by the key name.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.updateString("xyz", "1234") catch {};
json.updateString("abc.xyz", "1234") catch {};
json.updateString("abc.def", "1234") catch {};
json.updateString("abc.aaa", "1234") catch {};
json.updateString("ghi", "1234") catch {};
json.updateString("nmo", "1234") catch {};
json.setEmitCompact(false);
std.debug.print("{s}\n", .{try json.emit(alloc)});
// This is our initial JSON:
// {
// "xyz": "1234",
// "abc": {
// "xyz": "1234",
// "def": "1234",
// "aaa": "1234"
// },
// "ghi": "1234",
// "nmo": "1234"
// }
// Sort the top-level JSON object by key.
const ascending = true;
const case_sensitive = true;
json.sort(ascending, case_sensitive);
// Look at the sorted JSON..
std.debug.print("{s}\n", .{try json.emit(alloc)});
// {
// "abc": {
// "xyz": "1234",
// "def": "1234",
// "aaa": "1234"
// },
// "ghi": "1234",
// "nmo": "1234",
// "xyz": "1234"
// }
// Now sort the members of the "abc" object..
const json_abc = try chilkat.JsonObject.init();
defer json_abc.deinit();
json.objectOf2("abc", json_abc) catch {};
json_abc.sort(ascending, case_sensitive);
// Now look at the JSON with the members under "abc" also sorted..
std.debug.print("{s}\n", .{try json.emit(alloc)});
// {
// "abc": {
// "aaa": "1234",
// "def": "1234",
// "xyz": "1234"
// },
// "ghi": "1234",
// "nmo": "1234",
// "xyz": "1234"
// }
}