Zig
Zig
Find and Delete Object from JSON Array
See more JSON Examples
Demonstrates how to find an delete an object from a JSON array of objects.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// This example will delete the "Pasta" category object from Menu B.
// {
// "menus": [
// {
// "name": "Menu A",
// "categories": [
// {
// "name": "Kebabs",
// "description": "blah blah blah"
// },
// {
// "name": "Burgers",
// "description": "blah blah blah"
// },
// {
// "name": "Pasta",
// "description": "blah blah blah"
// },
// {
// "name": "Appetizers",
// "description": "blah blah blah"
// }
// ]
// },
// {
// "name": "Menu B",
// "categories": [
// {
// "name": "Kebabs",
// "description": "blah blah blah"
// },
// {
// "name": "Burgers",
// "description": "blah blah blah"
// },
// {
// "name": "Pasta",
// "description": "blah blah blah"
// },
// {
// "name": "Appetizers",
// "description": "blah blah blah"
// }
// ]
// }
// ]
// }
const json = try chilkat.JsonObject.init();
defer json.deinit();
json.loadFile("qa_data/json/menus.json") catch {
std.debug.print("{s}\n", .{try json.getLastErrorText(alloc)});
return;
};
// Find Menu B.
const menu = try json.findRecord("menus", "name", "Menu B", true);
defer menu.deinit();
// assume menu is found..
// Get the categories array, and then find the index of the "Pasta" menu category.
const cat_arr = try menu.arrayOf("categories");
defer cat_arr.deinit();
// Assume it is found..
// Find the object where the name of the JSON member is "name", and the value is "Pasta"
const index = cat_arr.findObject("name", "Pasta", true);
if (index < 0) {
std.debug.print("Pasta not found.\n", .{});
} else {
// Delete the "Pasta" category record from Menu B
try cat_arr.deleteAt(index);
// Assume OK..
}
// Examine the JSON to see if it worked as expected..
json.setEmitCompact(false);
std.debug.print("{s}\n", .{try json.emit(alloc)});
}