#How to use the zig's JSON stringify function.

1 messages · Page 1 of 1 (latest)

hearty totem
#

I am trying to convert a struct to a string using the standard library's json package, but i am getting an error saying type 'type' does not support field access which is coming from the json.stringify's definition.

#

Image reference

#

my attempt to call the function.

silver flare
#

You need to pass in a value of Block to stringify instead of the type itself

hearty totem
#

True!!, but still have the same issue.

hearty totem
silver flare
#

Im gonna guess it has to do with data

#

You need to pass in an impl of std.io.Writer for the third parameter

#

Easiest way is to change data to a std.ArrayList of u8, then pass in list.writer() for the third parameter (im on mobile so sorry I can’t write an example for ya 😅)

silver flare
silver flare
#

What’s Json? Is that an alias for std.json or?

hearty totem
#

yea, it's just an alias for std.json

silver flare
#

Ah okay

#
const std = @import("std");

const Point = struct {
    x: i32,
    y: i32,
};

pub fn main() !void {
    var point = Point{ .x = 1, .y = 2 };
    var serialized = std.ArrayList(u8).init(std.heap.page_allocator);
    defer serialized.deinit();

    try std.json.stringify(point, .{}, serialized.writer());

    std.debug.print("{s}\n", .{serialized.items});
}
#

something like this should work for ya

hearty totem
#

Oh okay, let me try this.

#

tried with your sample code, it worked on var point = .{ .x = 1, .y = 2 } but doesn't work with my struct.

silver flare
#

What’s your type look like? It may have a field that std.json doesn’t know how to serialize

hearty totem
#

just playing around with Block definitions.

silver flare
#

Ah

#

the allocator field’s the problem

hearty totem
#

oh!

#

how do you suggest i fix the issue??

silver flare
#

Yeah allocator’s got a bunch of weird stuff in it that std.json doesnt know how to handle

#

You can pass in an anonymous struct literal with just the fields you wan

#

.{ .prevHash = self.prevHash, … }

#

That’d be one way

hearty totem
#

yes, that's true, will try that...

#

Got this error

silver flare
#

Can you comment out the hashing code and see if you still get that?

hearty totem
#

okay...

#

still have the same issue

silver flare
#

Hm, should be working then

#

You’re setting all the struct fields to have values right?

hearty totem
#

not all of them tho.

#

by default i am setting some of them to be undefined.

#

that doesn't count as a value, does it?

silver flare
#

It does yeah, but you generally shouldn’t do that. Undefined’s kinda scary cause you can get segfaults like that

#

Better to leave them with no initial value or make them optional and have a default value of null

#

Or you can just give them a default value

hearty totem
#

will set a default value and run it again.

#

worked!!

#

Thanks man.

silver flare
#

No problem!