#Parsing a struct with nested structs in JSON

1 messages · Page 1 of 1 (latest)

whole canopy
#

Hey, so I'm trying to parse a json file. The structure is more or less like this

{
    "install_path": "/Users/JohnDoe/.local/bin",
    "packages": [
        {
            "url": "https://github.com/sharkdp/bat",
            "name": "bat",
            "tag": "latest"
        }
    ]
}

In my mind the way to parse this data would be to create a struct with a nested struct (within a std.MultiArrayList because there can be several) to pass to the std.json.TokenStream.init function, like this:

pub const PackageDecl = struct {
    url: []const u8,
    name: []const u8,
    tag: ?[]const u8 = "latest",
};

pub const Config = struct {
    install_path: []const u8,
    packages: std.MultiArrayList(PackageDecl),
};

However, I don't know what's going on when I pass my JSON file contents to the std.json library and try to parse it by using the following code chunk

var stream = std.json.TokenStream.init(config); // config is my JSON file contents string
try std.json.parse(Config, &stream, .{ .allocator = allocator });

I am getting this error and I am really confused about what is happening, why is it happening and how should I fix it? Thanks in advance!

#

Parsing a struct with nested structs in JSON

jolly basin
#

std.json doesn't know how to parse into a MultiArrayList, but you can use []const PackageDecl as the type of the packages field instead, which it will understand

whole canopy
#

Ah now it makes sense, thank you so much for the explanation and resources. Very appreciated!