Skip to content
Standard libraryZig 0.17.1Official documentation
Sourcestd/json.zig

Source line 1

JSON parsing and stringification conforming to RFC 8259. https://datatracker.ietf.org/doc/html/rfc8259

The low-level Scanner API produces Tokens from an input slice or successive slices of inputs, The Reader API connects a std.Io.Reader to a Scanner.

The high-level parseFromSlice and parseFromTokenSource deserialize a JSON document into a Zig type. Parse into a dynamically-typed Value to load any JSON value for runtime inspection.

The low-level writeStream emits syntax-conformant JSON tokens to a std.Io.Writer. The high-level stringify serializes a Zig or Value type into JSON.

std.json.AllocWhen

alias

Source line 76

Alias of std.json.Scanner.AllocWhen

std.json.Array

alias

Source line 64

Alias of std.json.dynamic.Array

std.json.ArrayHashMap

alias

Source line 67

Alias of std.json.hashmap.ArrayHashMap

std.json.builtin

constant

Source line 12

std.json.default_buffer_size

alias

Source line 72

Alias of std.json.Scanner.default_buffer_size

std.json.default_max_value_len

alias

Source line 77

Alias of std.json.Scanner.default_max_value_len

std.json.Diagnostics

alias

Source line 75

Alias of std.json.Scanner.Diagnostics

std.json.Error

alias

Source line 71

Alias of std.json.Scanner.Error

std.json.fmt

function

Source line 97

Returns a formatter that formats the given value using stringify.

pub fn fmt(value: anytype, options: Stringify.Options) Formatter(@TypeOf(value))

Parameters

options: Stringify.Options

Example usage

test fmt {
    const expectFmt = std.testing.expectFmt;
    try expectFmt("123", "{f}", .{fmt(@as(u32, 123), .{})});
    try expectFmt(
        \\{"num":927,"msg":"hello","sub":{"mybool":true}}
    , "{f}", .{fmt(struct {
        num: u32,
        msg: []const u8,
        sub: struct {
            mybool: bool,
        },
    }{
        .num = 927,
        .msg = "hello",
        .sub = .{ .mybool = true },
    }, .{})});
}

std.json.Formatter

type-function

Source line 120

Formats the given value using stringify.

pub fn Formatter(comptime T: type) type

Parameters

T: type

Fields

value: T
options: Stringify.Options

std.json.Formatter.format

function

Source line 125

pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void

Parameters

self: @This()
writer: *std.Io.Writer

Errors

WriteFailed

See the Writer implementation for detailed diagnostics.

std.json.innerParse

alias

Source line 87

Alias of std.json.static.innerParse

std.json.innerParseFromValue

alias

Source line 90

Alias of std.json.static.innerParseFromValue

std.json.isNumberFormattedLikeAnInteger

alias

Source line 79

Alias of std.json.Scanner.isNumberFormattedLikeAnInteger

std.json.ObjectMap

alias

Source line 63

Alias of std.json.dynamic.ObjectMap

std.json.Parsed

alias

Source line 82

Alias of std.json.static.Parsed

std.json.ParseError

alias

Source line 91

Alias of std.json.static.ParseError

std.json.parseFromSlice

alias

Source line 83

Alias of std.json.static.parseFromSlice

std.json.parseFromSliceLeaky

alias

Source line 84

Alias of std.json.static.parseFromSliceLeaky

std.json.parseFromTokenSource

alias

Source line 85

Alias of std.json.static.parseFromTokenSource

std.json.parseFromTokenSourceLeaky

alias

Source line 86

Alias of std.json.static.parseFromTokenSourceLeaky

std.json.parseFromValue

alias

Source line 88

Alias of std.json.static.parseFromValue

std.json.ParseFromValueError

alias

Source line 92

Alias of std.json.static.ParseFromValueError

std.json.parseFromValueLeaky

alias

Source line 89

Alias of std.json.static.parseFromValueLeaky

std.json.ParseOptions

alias

Source line 81

Alias of std.json.static.ParseOptions

std.json.Reader

alias

Source line 78

Alias of std.json.Scanner.Reader

std.json.Scanner

alias

Source line 69

Alias of std.json.Scanner

std.json.std

alias

Source line 13

Alias of std

std.json.Stringify

alias

Source line 94

Alias of std.json.Stringify

std.json.testing

alias

Source line 14

Alias of std.testing

std.json.Token

alias

Source line 73

Alias of std.json.Scanner.Token

std.json.TokenType

alias

Source line 74

Alias of std.json.Scanner.TokenType

std.json.validate

alias

Source line 70

Alias of std.json.Scanner.validate

std.json.Value

alias

Source line 65

Alias of std.json.dynamic.Value

Source code

std/json.zig

//! JSON parsing and stringification conforming to RFC 8259. https://datatracker.ietf.org/doc/html/rfc8259
//!
//! The low-level `Scanner` API produces `Token`s from an input slice or successive slices of inputs,
//! The `Reader` API connects a `std.Io.Reader` to a `Scanner`.
//!
//! The high-level `parseFromSlice` and `parseFromTokenSource` deserialize a JSON document into a Zig type.
//! Parse into a dynamically-typed `Value` to load any JSON value for runtime inspection.
//!
//! The low-level `writeStream` emits syntax-conformant JSON tokens to a `std.Io.Writer`.
//! The high-level `stringify` serializes a Zig or `Value` type into JSON.

const builtin = @import("builtin");
const std = @import("std");
const testing = std.testing;

test Scanner {
    var scanner = Scanner.initCompleteInput(testing.allocator, "{\"foo\": 123}\n");
    defer scanner.deinit();
    try testing.expectEqual(Token.object_begin, try scanner.next());
    try testing.expectEqualSlices(u8, "foo", (try scanner.next()).string);
    try testing.expectEqualSlices(u8, "123", (try scanner.next()).number);
    try testing.expectEqual(Token.object_end, try scanner.next());
    try testing.expectEqual(Token.end_of_document, try scanner.next());
}

test parseFromSlice {
    var parsed_str = try parseFromSlice([]const u8, testing.allocator, "\"a\\u0020b\"", .{});
    defer parsed_str.deinit();
    try testing.expectEqualSlices(u8, "a b", parsed_str.value);

    const T = struct { a: i32 = -1, b: [2]u8 };
    var parsed_struct = try parseFromSlice(T, testing.allocator, "{\"b\":\"xy\"}", .{});
    defer parsed_struct.deinit();
    try testing.expectEqual(@as(i32, -1), parsed_struct.value.a); // default value
    try testing.expectEqualSlices(u8, "xy", parsed_struct.value.b[0..]);
}

test Value {
    var parsed = try parseFromSlice(Value, testing.allocator, "{\"anything\": \"goes\"}", .{});
    defer parsed.deinit();
    try testing.expectEqualSlices(u8, "goes", parsed.value.object.get("anything").?.string);
}

test Stringify {
    var out: std.Io.Writer.Allocating = .init(testing.allocator);
    var write_stream: Stringify = .{
        .writer = &out.writer,
        .options = .{ .whitespace = .indent_2 },
    };
    defer out.deinit();
    try write_stream.beginObject();
    try write_stream.objectField("foo");
    try write_stream.write(123);
    try write_stream.endObject();
    const expected =
        \\{
        \\  "foo": 123
        \\}
    ;
    try testing.expectEqualSlices(u8, expected, out.written());
}

pub const ObjectMap = @import("json/dynamic.zig").ObjectMap;
pub const Array = @import("json/dynamic.zig").Array;
pub const Value = @import("json/dynamic.zig").Value;

pub const ArrayHashMap = @import("json/hashmap.zig").ArrayHashMap;

pub const Scanner = @import("json/Scanner.zig");
pub const validate = Scanner.validate;
pub const Error = Scanner.Error;
pub const default_buffer_size = Scanner.default_buffer_size;
pub const Token = Scanner.Token;
pub const TokenType = Scanner.TokenType;
pub const Diagnostics = Scanner.Diagnostics;
pub const AllocWhen = Scanner.AllocWhen;
pub const default_max_value_len = Scanner.default_max_value_len;
pub const Reader = Scanner.Reader;
pub const isNumberFormattedLikeAnInteger = Scanner.isNumberFormattedLikeAnInteger;

pub const ParseOptions = @import("json/static.zig").ParseOptions;
pub const Parsed = @import("json/static.zig").Parsed;
pub const parseFromSlice = @import("json/static.zig").parseFromSlice;
pub const parseFromSliceLeaky = @import("json/static.zig").parseFromSliceLeaky;
pub const parseFromTokenSource = @import("json/static.zig").parseFromTokenSource;
pub const parseFromTokenSourceLeaky = @import("json/static.zig").parseFromTokenSourceLeaky;
pub const innerParse = @import("json/static.zig").innerParse;
pub const parseFromValue = @import("json/static.zig").parseFromValue;
pub const parseFromValueLeaky = @import("json/static.zig").parseFromValueLeaky;
pub const innerParseFromValue = @import("json/static.zig").innerParseFromValue;
pub const ParseError = @import("json/static.zig").ParseError;
pub const ParseFromValueError = @import("json/static.zig").ParseFromValueError;

pub const Stringify = @import("json/Stringify.zig");

/// Returns a formatter that formats the given value using stringify.
pub fn fmt(value: anytype, options: Stringify.Options) Formatter(@TypeOf(value)) {
    return Formatter(@TypeOf(value)){ .value = value, .options = options };
}

test fmt {
    const expectFmt = std.testing.expectFmt;
    try expectFmt("123", "{f}", .{fmt(@as(u32, 123), .{})});
    try expectFmt(
        \\{"num":927,"msg":"hello","sub":{"mybool":true}}
    , "{f}", .{fmt(struct {
        num: u32,
        msg: []const u8,
        sub: struct {
            mybool: bool,
        },
    }{
        .num = 927,
        .msg = "hello",
        .sub = .{ .mybool = true },
    }, .{})});
}

/// Formats the given value using stringify.
pub fn Formatter(comptime T: type) type {
    return struct {
        value: T,
        options: Stringify.Options,

        pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void {
            try Stringify.value(self.value, self.options, writer);
        }
    };
}

test {
    _ = @import("json/test.zig");
    _ = Scanner;
    _ = @import("json/dynamic.zig");
    _ = @import("json/hashmap.zig");
    _ = @import("json/static.zig");
    _ = Stringify;
    _ = @import("json/JSONTestSuite_test.zig");
}