#Write data-structure out to JSON (custom types)

1 messages · Page 1 of 1 (latest)

pliant trail
#

Hey, I have a data-structure which might be nested. All the types represent Lua data-structures (nil, boolean, number, string, table, ...).

I am hoping I could plug into whatever machinery is provided by std.json.

I am searching the zig standard library code and found https://github.com/ziglang/zig/blob/6026bbd0adb445a0edd6defb0b378937dcce7a9b/lib/std/json/hashmap.zig

I'm having difficulty implementing, though.


const JsonSerializeError = error{
    UnsupportedValue,
};
const JsonWritable = struct {
    l: *Lua,
    ndx: i32,

    pub fn jsonStringify(self: @This(), jws: anytype) !void {
        const typ = self.l.typeOf(self.ndx);
        switch (typ) {
            .nil => {
                try jws.write(null);
            },
            .string => {
                const s = self.l.toString(self.ndx) catch {
                    return;
                };
                try jws.write(s);
            },
            else => {
                std.debug.print("json.dumps, unsupported value\n", .{});
                //return .OutOfMemory;
                // return JsonSerializeError.UnsupportedValue;
            },
        }
    }
};

If jsonStringify returns JsonSerializeError.UnsupportedValue, I get:

error: expected type 'error{OutOfMemory}!void', found '@typeInfo(@typeInfo(@TypeOf(engine.json.JsonWritable.jsonStringify__anon_12068)).Fn.return_type.?).ErrorUnion.error_set!void'
                        return value.jsonStringify(self);
                               ~~~~~~~~~~~~~~~~~~~^~~~~~
/home/jwd/apps/zig-linux-x86_64-0.13.0-dev.75+5c9eb4081/lib/std/json/stringify.zig:506:51: note: 'error.UnsupportedValue' not a member of destination error set
/home/jwd/apps/zig-linux-x86_64-0.13.0-dev.75+5c9eb4081/lib/std/json/stringify.zig:418:56: note: function return type declared here
        pub fn write(self: *Self, value: anytype) Error!void {

Is there no work-arounds ? Which errors CAN I return ?

pseudo forge
#

I think it's only supposed to return error.OutOfMemory or an error from the output stream, it's not supposed to fail.