#How to use the zig's JSON stringify function.
1 messages · Page 1 of 1 (latest)
You need to pass in a value of Block to stringify instead of the type itself
True!!, but still have the same issue.
this..
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 😅)
Oh
will try this..
What’s Json? Is that an alias for std.json or?
yea, it's just an alias for std.json
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
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.
What’s your type look like? It may have a field that std.json doesn’t know how to serialize
just playing around with Block definitions.
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
Can you comment out the hashing code and see if you still get that?
Hm, should be working then
You’re setting all the struct fields to have values right?
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?
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
No problem!