Sample code for 30+ languages & platforms
Zig

Iterate JSON where Member Names are Data Values

See more JSON Examples

Demonstrates how to parse JSON where member names are not keywords, but instead are data values.

Chilkat Zig Downloads

Zig
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();

    try json.loadFile("qa_data/json/valuesAsNames.json");

    // Imagine we have JSON such as the following:

    // {
    //   "1680": {
    //     "entity_id": "1680",
    //     "type_id": "simple",
    //     "sku": "123"
    //   },
    //   "1701": {
    //     "entity_id": "1701",
    //     "type_id": "simple",
    //     "sku": "456"
    //   }
    // }
    //

    // This presents a parsing problem because the member names, such as "1680"
    // are not keywords.  Instead they are data values.  We don't know what they
    // may be in advance.

    // To solve, we iterate over the members, get the name of each, ...
    const num_members = json.getSize();
    var i: i32 = 0;
    i = 0;
    while (i < num_members) : (i += 1) {
        const name = try json.nameAt(alloc, i);

        std.debug.print("{s}:\n", .{name});
        const j_record = try json.objectAt(i);
        defer j_record.deinit();

        std.debug.print("entity_id: {s}\n", .{try j_record.stringOf(alloc, "entity_id")});
        std.debug.print("type_id: {s}\n", .{try j_record.stringOf(alloc, "type_id")});
        std.debug.print("sku: {s}\n", .{try j_record.stringOf(alloc, "sku")});
    }
}