JSON iterate over fields

Hi,

I have a JSON file:

{
    "a": 1,
    "b":{
        "c": 2
    },  
    "d": [3,4]
}

and I parse read it in with the following code:

const std = @import("std");
const Json = std.json.Value;

const input = @embedFile("file.json");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    var json = try std.json.parseFromSlice(Json, allocator, input, .{});
    defer json.deinit();

    const root = json.value.object;
}

From there I could get the top level fields by e.g. root.get("a") or root.get("b").
But what if I don’t know the keys and I would simply like to iterate over all keys in the current level.
Is there an iterator? Unfortunately I could not find anything in the stdlib, but I have to admit, that I am lost in the stdlib quite often.
Thanks for your help.

std.json.Value.object is actually std.StringArrayHashMap(Value) so you can use all its methods.
To iterate over all keys you would write

for (root.keys()) |key| {
    std.debug.print("{s}\n", .{key});
}
2 Likes

Thank you.