Skip to content

Zig JSON

JSON is everywhere: config files, web APIs, data you save between runs. Zig’s standard library has std.json, which turns JSON text into your own structs and turns structs back into JSON, with no extra packages. This page shows how to parse into a struct, what happens when the JSON doesn’t match it, how to write JSON out, and what to do when you don’t know the shape in advance. One rule comes up again and again: the parsed data lives in memory that you must free, and only until you free it.

You describe the shape you expect as a normal Zig struct, and std.json.parseFromSlice fills it in:

const std = @import("std");
const User = struct {
name: []const u8,
age: u32,
admin: bool,
};
pub fn main(init: std.process.Init) !void {
const text =
\\{ "name": "Ada", "age": 36, "admin": true }
;
const parsed = try std.json.parseFromSlice(User, init.gpa, text, .{});
defer parsed.deinit();
const user = parsed.value;
std.debug.print("{s} is {d}, admin: {}\n", .{ user.name, user.age, user.admin });
}

Output:

Ada is 36, admin: true

The four arguments are the type you want, an allocator, the JSON text, and options (.{} for the defaults). Inside the struct, field names must match the JSON keys exactly, including upper and lower case.

The text uses a multiline string literal (lines starting with \\) so the quotes inside don’t need escaping. You’ll usually read the JSON from a file instead; that comes below.

parseFromSlice doesn’t return a User directly. It returns a std.json.Parsed(User), which holds two things:

  • parsed.value: your User.
  • An arena with every allocation the parser made: copies of strings, slices for arrays, and so on.

parsed.deinit() frees all of it in one go, which is why defer parsed.deinit(); goes on the very next line. The flip side: everything inside parsed.value is only valid until deinit. If you need some of it longer, copy it out first (for example with gpa.dupe). Zig Arena Allocator explains why one arena for the whole result is handy here.

You choose the Zig types, and the parser checks the JSON against them:

JSON Zig type in your struct
object {...} a struct with matching field names
array [...] a slice like []const u32 or []const Item (or a fixed array [3]u32)
string "..." []const u8, or an enum (the string must be a tag name)
number any integer or float type, like u16, i64, f64
true / false bool
null an optional, like ?[]const u8

Nested objects are just nested structs. This config has a list and a nested object:

const std = @import("std");
const Server = struct {
host: []const u8,
port: u16,
};
const Config = struct {
app: []const u8,
servers: []const Server,
tags: []const []const u8,
};
pub fn main(init: std.process.Init) !void {
const text =
\\{
\\ "app": "shop",
\\ "servers": [
\\ { "host": "eu.example.com", "port": 8080 },
\\ { "host": "us.example.com", "port": 9090 }
\\ ],
\\ "tags": ["web", "prod"]
\\}
;
const parsed = try std.json.parseFromSlice(Config, init.gpa, text, .{});
defer parsed.deinit();
const config = parsed.value;
std.debug.print("app {s}, {d} tags\n", .{ config.app, config.tags.len });
for (config.servers) |s| {
std.debug.print(" {s}:{d}\n", .{ s.host, s.port });
}
}

Output:

app shop, 2 tags
eu.example.com:8080
us.example.com:9090

Picking a precise type pays off: port: u16 means a port of 70000 is rejected while parsing, instead of causing trouble later.

Missing fields, defaults and unknown fields

Section titled “Missing fields, defaults and unknown fields”

Real JSON rarely matches your struct perfectly. Here’s how the parser reacts to the usual differences. The helper tryParse parses one string and prints the result or the error:

const std = @import("std");
const User = struct {
name: []const u8,
age: u32,
admin: bool = false,
email: ?[]const u8 = null,
};
fn tryParse(gpa: std.mem.Allocator, text: []const u8, options: std.json.ParseOptions) void {
const parsed = std.json.parseFromSlice(User, gpa, text, options) catch |err| {
std.debug.print("{s} -> error.{t}\n", .{ text, err });
return;
};
defer parsed.deinit();
const u = parsed.value;
std.debug.print("{s} -> {s}, {d}, admin={}, email={?s}\n", .{ text, u.name, u.age, u.admin, u.email });
}
pub fn main(init: std.process.Init) void {
const gpa = init.gpa;
tryParse(gpa, "{\"name\":\"Ada\",\"age\":36}", .{});
tryParse(gpa, "{\"name\":\"Ada\",\"age\":36,\"email\":\"[email protected]\"}", .{});
tryParse(gpa, "{\"name\":\"Ada\"}", .{});
tryParse(gpa, "{\"name\":\"Ada\",\"age\":36,\"city\":\"London\"}", .{});
tryParse(gpa, "{\"name\":\"Ada\",\"age\":36,\"city\":\"London\"}", .{ .ignore_unknown_fields = true });
}

Output:

{"name":"Ada","age":36} -> Ada, 36, admin=false, email=null
{"name":"Ada","age":36,"email":"[email protected]"} -> Ada, 36, admin=false, [email protected]
{"name":"Ada"} -> error.MissingField
{"name":"Ada","age":36,"city":"London"} -> error.UnknownField
{"name":"Ada","age":36,"city":"London"} -> Ada, 36, admin=false, email=null

The rules:

  • A field with a default value (admin: bool = false) may be missing from the JSON; the default is used. The reference covers default field values.
  • A field without a default must be there, or you get error.MissingField. Here age has no default.
  • For “might be missing or null”, use an optional with a default: email: ?[]const u8 = null. It accepts a missing key, "email": null, and a string.
  • A key in the JSON that your struct doesn’t have gives error.UnknownField. That’s strict on purpose: it catches typos like "nmae". For data from a web API, which may add new fields any day, pass .{ .ignore_unknown_fields = true }.

Broken or mismatched JSON gives an error. Here are the ones you’ll meet, from the same tryParse helper:

{"name":"Ada","age":-1} -> error.Overflow
{"name":"Ada","age":36.5} -> error.InvalidNumber
{"name":"Ada","age":36,} -> error.SyntaxError
{"name":"Ada","age":36 -> error.UnexpectedEndOfInput
{"name":"Ada","age":36,"age":37} -> error.DuplicateField

-1 doesn’t fit in a u32, 36.5 isn’t a whole number, a trailing comma isn’t valid JSON (unlike JavaScript), the last one is cut off, and a repeated key is an error unless you set .duplicate_field_behavior. One surprise in the other direction: "age": "36", a number inside a string, is accepted for an integer field.

The error name alone doesn’t say where the problem is, which hurts in a 200-line config file. For that, parse through a Scanner with diagnostics switched on:

const std = @import("std");
const Config = struct { name: []const u8, port: u16 };
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const text =
\\{
\\ "name": "web",
\\ "port": 80,80
\\}
;
var scanner = std.json.Scanner.initCompleteInput(gpa, text);
defer scanner.deinit();
var diagnostics: std.json.Diagnostics = .{};
scanner.enableDiagnostics(&diagnostics);
const parsed = std.json.parseFromTokenSource(Config, gpa, &scanner, .{}) catch |err| {
std.debug.print("error.{t} at line {d}, column {d}\n", .{ err, diagnostics.getLine(), diagnostics.getColumn() });
return;
};
defer parsed.deinit();
std.debug.print("port {d}\n", .{parsed.value.port});
}

Output:

error.SyntaxError at line 3, column 14

Column 14 on line 3 is the second 80, right where the JSON stopped making sense. parseFromSlice does exactly this internally, minus the diagnostics, so this is the same parser with better error messages.

Watch out: strings can point into your input

Section titled “Watch out: strings can point into your input”

To save memory, the parser doesn’t always copy strings. When a string in the JSON has no escapes (no \n, \" and so on), the []const u8 in your struct may point straight into the text you passed in. That’s fine as long as the text stays alive. It becomes a bug when you free the text first:

const text = try cwd.readFileAlloc(io, "user.json", gpa, .limited(1024 * 1024));
const parsed = try std.json.parseFromSlice(User, gpa, text, .{});
defer parsed.deinit();
gpa.free(text); // too early!
std.debug.print("{s}\n", .{parsed.value.name}); // garbage

The name now points at freed memory, and you’ll see junk characters (in debug builds the freed bytes get overwritten on purpose, so it’s easy to spot). Two fixes:

  • Keep the text alive as long as you use the parsed value: defer gpa.free(text); before the defer parsed.deinit();, so it’s freed after.
  • Or ask for copies with .{ .allocate = .alloc_always }. Then everything lives in the Parsed arena, and you can free the text right away.

Putting it together with Zig File I/O: this program saves a list of tasks as JSON, then loads it back. It uses std.json.Stringify.value to write JSON into any writer, here a file writer:

const std = @import("std");
const Priority = enum { low, normal, high };
const Task = struct {
title: []const u8,
done: bool = false,
priority: Priority = .normal,
};
pub fn main(init: std.process.Init) !void {
const io = init.io;
const gpa = init.gpa;
const cwd = std.Io.Dir.cwd();
const tasks = [_]Task{
.{ .title = "learn Zig", .priority = .high },
.{ .title = "water plants", .done = true },
};
// Save
{
const file = try cwd.createFile(io, "tasks.json", .{});
defer file.close(io);
var buffer: [1024]u8 = undefined;
var file_writer = file.writer(io, &buffer);
try std.json.Stringify.value(tasks, .{ .whitespace = .indent_2 }, &file_writer.interface);
try file_writer.interface.flush();
}
defer cwd.deleteFile(io, "tasks.json") catch {};
// Load
const text = try cwd.readFileAlloc(io, "tasks.json", gpa, .limited(1024 * 1024));
defer gpa.free(text);
std.debug.print("{s}\n", .{text});
const parsed = try std.json.parseFromSlice([]Task, gpa, text, .{});
defer parsed.deinit();
for (parsed.value) |t| {
std.debug.print("[{s}] {s} ({t})\n", .{ if (t.done) "x" else " ", t.title, t.priority });
}
}

Output:

[
{
"title": "learn Zig",
"done": false,
"priority": "high"
},
{
"title": "water plants",
"done": true,
"priority": "normal"
}
]
[ ] learn Zig (high)
[x] water plants (normal)

A few things worth noticing:

  • Enums become their tag name as a string ("high"), and parse back from it. An unknown name like "urgent" fails with error.InvalidEnumTag.
  • The top level of the file is an array, so the program parses []Task, a slice of tasks.
  • text is freed by a defer written before defer parsed.deinit(), so it’s freed after it: the safe order from the previous section.
  • The save happens in its own { } block, so the file is closed (and flushed) before the program reads it back.

Stringify.value writes to a writer. Two more ways cover most other needs:

const std = @import("std");
const Player = struct {
name: []const u8,
score: u32,
friends: []const []const u8,
nickname: ?[]const u8 = null,
};
pub fn main(init: std.process.Init) !void {
const p: Player = .{ .name = "Ada", .score = 1200, .friends = &.{ "Bob", "Cy" } };
// 1. Straight into a print, with {f}
std.debug.print("{f}\n", .{std.json.fmt(p, .{})});
std.debug.print("{f}\n", .{std.json.fmt(p, .{ .whitespace = .indent_2, .emit_null_optional_fields = false })});
// 2. Into a new string you own
const text = try std.json.Stringify.valueAlloc(init.gpa, p, .{});
defer init.gpa.free(text);
std.debug.print("{d} bytes\n", .{text.len});
}

Output:

{"name":"Ada","score":1200,"friends":["Bob","Cy"],"nickname":null}
{
"name": "Ada",
"score": 1200,
"friends": [
"Bob",
"Cy"
]
}
66 bytes
  • std.json.fmt(value, options) makes something you can print with {f}, with any print function: std.debug.print, a stdout writer, a file writer. (Zig Format Strings covers {f}.)
  • std.json.Stringify.valueAlloc(gpa, value, options) gives you the JSON as a []u8 that you free yourself. Handy when you need to send or store the text.
  • The default is minified: no spaces or newlines. .whitespace = .indent_2 makes it readable for humans.
  • .emit_null_optional_fields = false leaves out fields that are null instead of writing "nickname":null.

Strings are escaped for you, so a name containing " or a newline still produces valid JSON.

Sometimes you can’t write a struct up front: a tool that pretty-prints any JSON, or an API response where you only need one field. Parse into std.json.Value instead. It’s a tagged union that can hold any JSON value: .null, .bool, .integer, .float, .string, .array or .object.

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const text =
\\{ "name": "zigtutorial", "version": 3, "tags": ["zig", "tutorial"], "owner": null }
;
const parsed = try std.json.parseFromSlice(std.json.Value, init.gpa, text, .{});
defer parsed.deinit();
const root = parsed.value.object;
// You know the shape: read fields directly.
const name = root.get("name").?.string;
const version = root.get("version").?.integer;
std.debug.print("{s} v{d}\n", .{ name, version });
for (root.get("tags").?.array.items) |tag| {
std.debug.print("tag: {s}\n", .{tag.string});
}
// You don't know the shape: look at each value's tag.
var it = root.iterator();
while (it.next()) |entry| {
switch (entry.value_ptr.*) {
.string => |s| std.debug.print("{s} is the string \"{s}\"\n", .{ entry.key_ptr.*, s }),
.integer => |n| std.debug.print("{s} is the number {d}\n", .{ entry.key_ptr.*, n }),
else => |v| std.debug.print("{s} is {t}\n", .{ entry.key_ptr.*, v }),
}
}
if (root.get("missing") == null) std.debug.print("no key 'missing'\n", .{});
}

Output:

zigtutorial v3
tag: zig
tag: tutorial
name is the string "zigtutorial"
version is the number 3
tags is array
owner is null
no key 'missing'
  • parsed.value.object is a map from keys to Values (keys keep their order from the JSON). get returns null for a missing key, so .? is “I’m sure it’s there”.
  • .string, .integer, .array.items read the value as that kind. If it’s a different kind, say the JSON has "version": "3", you get a panic: access of union field 'integer' while field 'string' is active.
  • With data you don’t control, switch on the value instead, as the loop does. Whole numbers come back as .integer (i64), numbers with a dot or exponent as .float.

Value is flexible but wordy. When you know the shape, a struct is shorter, checks more for you and gives better errors. A common middle ground is a struct with only the fields you need plus .ignore_unknown_fields = true.

Parse this JSON into a slice of structs and print how many tasks are done:

[{"title":"buy milk","done":true},{"title":"call mom","done":false},{"title":"write code","done":true}]

Hint: define const Todo = struct { title: []const u8, done: bool }; and parse []Todo.

Show solution
const std = @import("std");
const Todo = struct {
title: []const u8,
done: bool,
};
pub fn main(init: std.process.Init) !void {
const text =
\\[{"title":"buy milk","done":true},{"title":"call mom","done":false},{"title":"write code","done":true}]
;
const parsed = try std.json.parseFromSlice([]Todo, init.gpa, text, .{});
defer parsed.deinit();
var done: usize = 0;
for (parsed.value) |todo| {
if (todo.done) done += 1;
}
std.debug.print("{d} of {d} done\n", .{ done, parsed.value.len });
}

Output:

2 of 3 done

A JSON array at the top level becomes a slice, and parsed.value.len is the number of items.

An API sends {"id":7,"login":"ada","bio":"...","followers":120,"site":"..."}. Parse it into a struct with only login and followers, and print them.

Hint: without the right option, the extra fields give error.UnknownField.

Show solution
const std = @import("std");
const Profile = struct {
login: []const u8,
followers: u32,
};
pub fn main(init: std.process.Init) !void {
const text =
\\{"id":7,"login":"ada","bio":"Writes Zig","followers":120,"site":"example.com"}
;
const parsed = try std.json.parseFromSlice(Profile, init.gpa, text, .{ .ignore_unknown_fields = true });
defer parsed.deinit();
std.debug.print("{s} has {d} followers\n", .{ parsed.value.login, parsed.value.followers });
}

Output:

ada has 120 followers

.ignore_unknown_fields = true skips id, bio and site. This is the usual setup for web APIs, which can add fields at any time.

Make a Point struct with x: i32 and y: i32, turn .{ .x = 3, .y = -4 } into a JSON string with valueAlloc, print it, then parse it back and print x + y.

Hint: std.json.Stringify.valueAlloc(gpa, value, .{}) returns []u8 you must free.

Show solution
const std = @import("std");
const Point = struct { x: i32, y: i32 };
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const text = try std.json.Stringify.valueAlloc(gpa, Point{ .x = 3, .y = -4 }, .{});
defer gpa.free(text);
std.debug.print("{s}\n", .{text});
const parsed = try std.json.parseFromSlice(Point, gpa, text, .{});
defer parsed.deinit();
std.debug.print("x + y = {d}\n", .{parsed.value.x + parsed.value.y});
}

Output:

{"x":3,"y":-4}
x + y = -1

The same struct type works in both directions, so whatever you save, you can load back.

  • std.json.parseFromSlice(T, gpa, text, .{}) parses JSON into your type. defer parsed.deinit(), and use parsed.value only until then.
  • JSON objects map to structs, arrays to slices, strings to []const u8 or enums, null to optionals.
  • Missing field: give it a default. Extra fields: .ignore_unknown_fields = true. Otherwise you get MissingField / UnknownField.
  • Parsed strings may point into your input text: keep the text alive, or use .allocate = .alloc_always.
  • Write JSON with std.json.fmt(v, .{}) and {f}, Stringify.valueAlloc, or Stringify.value into a writer. .whitespace = .indent_2 for humans.
  • For unknown shapes, parse into std.json.Value and switch on it.

Next up: Zig Processes, starting other programs from Zig and reading what they print.

Quick check

1. Your struct has age: u32 with no default, and the JSON has no "age" key. What happens?
2. An API response has extra keys your struct doesn't list. How do you parse it without an error?
3. You free the JSON text right after parseFromSlice, and later parsed.value.name prints garbage. Why?
4. How do you print a Zig struct as JSON with std.debug.print?