Zig Requires Chilkat v11.0.0+
Zig
Swap JSON Objects
See more JSON Examples
Demonstrates how to swap two JSON objects within a JSON document.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);
// Load the following JSON:
// {
// "petter": {
// "DOB": "26/02/1986",
// "gender": "male",
// "country": "US"
// },
// "Sara": {
// "DOB": "13/05/1982",
// "gender": "female",
// "country": "FR"
// },
// "Jon": {
// "DOB": "19/03/1984",
// "gender": "male",
// "country": "UK"
// }
// }
json.loadFile("qa_data/json/people.json") catch {
std.debug.print("{s}\n", .{try json.getLastErrorText(alloc)});
return;
};
// Swap the positions of Jon and Sara.
var index1: i32 = json.indexOf("Jon");
var index2: i32 = json.indexOf("Sara");
json.swap(index1, index2) catch {};
// We have this now:
std.debug.print("{s}\n", .{try json.emit(alloc)});
// {
// "petter": {
// "DOB": "26/02/1986",
// "gender": "male",
// "country": "US"
// },
// "Jon": {
// "DOB": "19/03/1984",
// "gender": "male",
// "country": "UK"
// },
// "Sara": {
// "DOB": "13/05/1982",
// "gender": "female",
// "country": "FR"
// }
// }
// To swap an inner member:
const json_sara = try chilkat.JsonObject.init();
defer json_sara.deinit();
json.objectOf2("Sara", json_sara) catch {};
index1 = json_sara.indexOf("DOB");
index2 = json_sara.indexOf("country");
json_sara.swap(index1, index2) catch {};
// We now have this:
std.debug.print("{s}\n", .{try json.emit(alloc)});
// {
// "petter": {
// "DOB": "26/02/1986",
// "gender": "male",
// "country": "US"
// },
// "Jon": {
// "DOB": "19/03/1984",
// "gender": "male",
// "country": "UK"
// },
// "Sara": {
// "country": "FR",
// "gender": "female",
// "DOB": "13/05/1982"
// }
// }
}