Static JSON encoding and decoding for Zig, driven by your types. Designed to be used for APIs with strict schemas.
Everything is comptime-specialized into the type being encoded or decoded:
there is no Value, no tokenizer, and no runtime schema. Encoding writes to a
std.Io.Writer and decoding reads from a std.Io.Reader, so both work against
sockets and files, not only complete buffers. Due to the static nature, it's much
faster than std.json, especially at decoding.
- Add json.zig as a dependency in your
build.zig.zon:
zig fetch --save "git+https://github.com/lalinsky/json.zig?ref=v0.2.0"- In your
build.zig, add thejsonmodule as a dependency of your program:
const json = b.dependency("json", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("json", json.module("json"));Requires Zig 0.16 or 0.17.
const std = @import("std");
const json = @import("json");
const Message = struct {
name: []const u8,
age: u8,
};
var buffer: std.Io.Writer.Allocating = .init(allocator);
defer buffer.deinit();
try json.encode(Message{ .name = "John", .age = 20 }, &buffer.writer);
// {"name":"John","age":20}
const decoded = try json.decodeFromSlice(Message, allocator, buffer.written(), .{});
defer decoded.deinit();
std.debug.assert(decoded.value.age == 20);decodeFromSlice creates an arena of its own for the decoded value, which is
what deinit frees. If you are already decoding into memory you release in one
go, such as a per-request arena or a fixed buffer, use decodeFromSliceLeaky
instead. It allocates straight from the allocator you give it, so there is
nothing to deinit, and it avoids a second arena inside your own:
var arena: std.heap.ArenaAllocator = .init(allocator);
defer arena.deinit();
const message = try json.decodeFromSliceLeaky(Message, arena.allocator(), bytes, .{});On failure a leaky decode does not release what it already allocated, so give
it an allocator you can discard wholesale. decode owns an arena and frees it
on error.
The last argument is json.DecodeOptions, which applies to the whole decode.
.{} is the strict default; .{ .skip_unknown_fields = true } steps over
object members matching no field, in every type the decode reaches. That is the
same thing a type can ask for itself below, for when the type is not yours to
change.
There is also json.encodeAlloc(gpa, value) when you just want a slice.
Decode errors use std.json's names wherever std.json has the same case.
Input that is not well-formed JSON is error.SyntaxError. Valid JSON with the
wrong kind of value for the type, such as a string where a number belongs or
null for a field that is not optional, is error.UnexpectedToken. Only the
first byte of such a value is looked at, so the rest of it is not checked. A
number that does not fit its type is error.Overflow.
decodeLeaky takes a reader, and decode does too:
const message = try json.decodeLeaky(Message, arena.allocator(), &reader, .{});The reader's buffer may be far smaller than the values being decoded. Strings, numbers and skipped values are all consumed incrementally, so a 1 MB string decodes fine through a 64-byte buffer. The buffer must hold at least 8 bytes.
A decode reads one document, and anything after it other than whitespace is
error.TrailingData. With .{ .allow_trailing_data = true }, the decode stops
after the value and leaves the reader there, so the next decode reads the next
document. That is how a stream of documents, such as NDJSON, is read.
By default a struct is an object keyed by field name, and optional fields that
are null are left out entirely. Change that by declaring jsonFormat:
const Message = struct {
user_id: u32,
nickname: ?[]const u8,
pub fn jsonFormat() json.StructOptions {
return .{
.key = .custom,
.skip_unknown_fields = true,
.omit_null_fields = false,
};
}
pub fn jsonFieldName(comptime field: std.meta.FieldEnum(@This())) []const u8 {
return switch (field) {
.user_id => "userId",
.nickname => "nickname",
};
}
};A field appearing twice in one object is error.DuplicateField, matching
std.json. skip_unknown_fields steps over object members whose key matches no field,
instead of failing with error.UnknownField. It lets a consumer read documents
from a newer producer that added fields. Missing fields are already accepted
without any option, as long as they have a default value or are optional.
A type declaring skip_unknown_fields and a decode passing it are ored, never
overridden: whichever of the two is more permissive wins.
A tagged union is encoded as a one-member object keyed by the variant name:
{"circle":{"radius":2.5}}Declaring jsonFormat switches it to the flattened form, where the variant's
own fields sit next to a tag field:
const Shape = union(enum) {
circle: struct { radius: f64 },
rect: struct { w: u32, h: u32 },
pub fn jsonFormat() json.UnionFormat {
return .{ .as_tagged = .{ .tag_field = "type", .skip_unknown_fields = false } };
}
};{"type":"circle","radius":2.5}as_tagged needs every variant to carry a struct or void, since there is
nothing to hoist otherwise (a tuple has no names to hoist either), and the tag must be the object's first member.
Anything else would mean buffering the whole object before knowing which
variant to build, which a streaming decoder cannot do.
A type can take over its own encoding entirely:
const Point = struct {
x: f64,
y: f64,
pub fn jsonWrite(self: Point, encoder: json.Encoder) !void {
try encoder.write(&[_]f64{ self.x, self.y });
}
pub fn jsonRead(decoder: *json.Decoder) !Point {
const pair = try decoder.value([2]f64);
return .{ .x = pair[0], .y = pair[1] };
}
};For a shape no type describes, both sides can go piece by piece.
encoder.object() and decoder.object() write and read an object one member
at a time, which is how a map is written and read:
const Scores = struct {
map: std.StringHashMapUnmanaged(u32),
pub fn jsonWrite(self: Scores, encoder: json.Encoder) !void {
var members = try encoder.object();
var it = self.map.iterator();
while (it.next()) |entry| {
try members.field(entry.key_ptr.*, entry.value_ptr.*);
}
try members.end();
}
pub fn jsonRead(decoder: *json.Decoder) !Scores {
var map: std.StringHashMapUnmanaged(u32) = .empty;
var members = try decoder.object();
while (try members.next()) |key| {
try map.put(decoder.gpa, key, try decoder.value(u32));
}
return .{ .map = map };
}
};When writing, field writes a whole member, and the commas between members
are put in for you. To write a value that has to be built piece by piece
itself, call key and then write the value with the encoder's write,
object or array. encoder.array() works the same way, with item, and
next followed by the value.
When reading, after each key, read the member's value with value,
skipValue, object or array before asking for the next key. Keys are
allocated with the decoder's allocator. decoder.array() works the same way:
while next() returns true, read one item.
An object or array opened this way has to be read to its end, or the reader
can't tell where it stops. To stop early, call skipRest() instead of
next(). Asking a reader for more before the value inside it is finished, or
returning from jsonRead with one unfinished, panics.
decoder.peek() tells you what kind of value comes next, without consuming
it, for a value that can come in more than one form:
const UserRef = union(enum) {
id: u64,
name: []const u8,
pub fn jsonRead(decoder: *json.Decoder) !UserRef {
return switch (try decoder.peek()) {
.number => .{ .id = try decoder.value(u64) },
.string => .{ .name = try decoder.value([]const u8) },
else => error.UnexpectedToken,
};
}
};Objects and arrays read this way count toward the depth limit like any other.
error.ReadFailed from jsonRead means the decoder's own reader failed. A jsonRead that reads
from another reader, such as a decompressor, has to return a different error when that one fails.
| Zig | JSON |
|---|---|
bool |
true / false |
| integers | number |
| floats | number (null for NaN and infinities) |
[]const u8 |
string (validated as UTF-8) |
| slices, arrays | array |
| structs | object |
| tuples | array |
?T |
null, or the encoding of T |
| enums | string naming the tag (see below) |
| tagged unions | one-member object, or flattened (see below) |
void |
null |
Sentinel-terminated arrays and slices, such as [:0]const u8, map the same
way as their plain counterparts, and get their sentinel when decoded.
Many-item pointers such as [*:0]const u8 are not supported. A \u0000 in
the input decodes to a NUL inside the string, so a [:0]const u8 handed to C
can look shorter than it is.
A value of a non-exhaustive enum with no named tag is written as its integer.
A non-exhaustive enum decodes from either form, and a number that names a tag
decodes to that tag. Numbers outside the tag type are error.Overflow.
Encoding a NaN or infinity as null matches what JavaScript's
JSON.stringify does. Pass .{ .non_finite = .fail } to
encodeWithOptions to get error.NonFiniteFloat instead.
Strings are validated as UTF-8 on the way in, so a decoded []const u8 is
always well-formed. Pure-ASCII strings do not pay for the check: the scan
detects non-ASCII bytes in the same pass that finds the end of the string.
The speed comes from doing less work rather than from tricks. There is no tokenizer: the function that decodes a struct is generated from that struct's fields, and bytes go straight into the result. Object keys are matched as whole comptime-known tokens rather than read as strings and looked up, integers accumulate in the same pass that finds the end of the number, strings are scanned in blocks and copied in runs, and reads take a fast path directly out of the reader's buffer when the value is already there.
There is no Value type, and no built-in support for maps or untagged
unions. A jsonRead can read any of them with object, array and peek,
as shown above. Comments and trailing commas in input are rejected.
Nesting deeper than 256 levels is rejected.
zig build conformance runs JSONTestSuite, the standard suite for
RFC 8259 parsers. All 95 must-accept and 188 must-reject cases pass.
Every case runs twice: once through validate, and once decoded into real Zig
types. For the must-reject cases, every candidate type has to refuse the
document.
Of the 35 cases the suite leaves implementation-defined, this library rejects
invalid UTF-8, malformed \u surrogate pairs, UTF-16 input, byte-order marks,
and nesting past its depth limit. It accepts numbers that overflow or underflow
the destination type, which decode to infinity or zero.
Its cases are vendored under test/JSONTestSuite, so the run is offline and
needs no network.
MIT