I’m trying to read in a json file in zig and then parse it to a struct.
The json I want to read is here, yes I have verified it is correct json.
I created these structs to hold the parsed data:
pub const Mb32Data = struct {
name: []const u8,
initial: Mb32Initial,
final: Mb32Initial,
cycles: []Mb32Cycles,
};
pub const Mb32Initial = struct {
pc: u16,
sp: u16,
a: u8,
b: u8,
c: u8,
d: u8,
e: u8,
f: u8,
h: u8,
l: u8,
ime: u2,
ei: u2,
ram: [][]const u8,
};
pub const Mb32Cycles = struct {
address: u16,
data: u8,
ignore: []u8,
};
And this is the code I’m using to parse the json:
fn open_test(path: []const u8) !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var file = try std.fs.cwd().openFile(path, .{});
defer file.close();
const allocator = gpa.allocator();
const contents = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
const json = try std.json.parseFromSlice([]Mb32Data, allocator, contents, .{ .allocate = .alloc_always, .ignore_unknown_fields = true });
const value = json.value;
std.debug.print("name is {any}", .{value[0].name});
}
This keeps failing with very cryptic hard to understand errors like this
if (ov[1] != 0) return error.Overflow
or
return error.MissingField;
Is there an easy way to debug why the json is not parsing correctly?
edit:
The main problem was I was trying to use a named struct with fields but using anynomous structs fixed the issue. Thank you everyone for the help.
pub const Mb32Data = struct {
name: []const u8,
initial: Mb32Initial,
final: Mb32Initial,
cycles: []struct { u16, u8, []const u8 }, <---- this
};
pub const Mb32Initial = struct {
pc: u16,
sp: u16,
a: u8,
b: u8,
c: u8,
d: u8,
e: u8,
f: u8,
h: u8,
l: u8,
ime: u2,
ie: u2 = 0,
ram: []struct { u16, u8 }, <---- and this
};