Stringifying arbitrary json

Hey, welcome to Ziggit!

The problem here is that you’re using the wrong kind of writer.

Zig currently uses implicit interfaces for readers and writers which can be quite confusing because they’re labeled anytype anywhere they’re required as an argument, so basically there’s only the name of the parameter to tell you that a reader or a writer is needed here (there are plans to change that).

However std.json has a bunch of specialized readers and writers. This is as of now only indicated by the argument for std.json.Value.jsonStringify being called jws (JSON write stream) instead of writer. The compiler doesn’t complain as much as it probably should here if you use the wrong writer interface because both std.json.WriteStream and std.io.Writer (which is what arr.writer() returns) happen to have a write function, however std.io.Writer.write indeed only accepts []const u8 as a parameter, so if you try to .write(null) (which is supported by std.json.WriteStream.write) you will get an error.

This means that you have to wrap your std.ArrayList writer in a std.json.WriteStream first before you can supply it to std.json.Value.jsonStringify like this:

[...]
var arr = std.ArrayList(u8).init(allocator);
var jws = std.json.writeStream(arr.writer(), .{});
try parsed.value.jsonStringify(&jws);

EDIT: Or just use std.json.stringify(), see @stratts reply

3 Likes