Quick Start ​
zig
const std = @import("std");
const z = @import("zigantic");
const Address = struct { city: []const u8, postal_code: []const u8 };
const AddressSchema = z.object(Address, .{
.city = z.string(.{ .min = 1 }),
.postal_code = z.string(.{ .len = 5, .charset = .numeric }),
}, .{});
const User = struct {
name: []const u8,
email: []const u8,
age: u8,
address: Address,
};
const UserSchema = z.object(User, .{
.name = z.string(.{ .min = 1, .trim = true }),
.email = z.email(.{}),
.age = z.integer(u8, .{ .min = 18 }),
.address = AddressSchema,
}, .{});
pub fn main() !void {
const allocator = std.heap.page_allocator;
var result = try z.parse(UserSchema, allocator,
\{"name":"Ada","email":"ada@example.com","age":36,"address":{"city":"London","postal_code":"12345"}}
, .{});
defer result.deinit();
if (result.value) |user| {
std.debug.print("{s} in {s}\n", .{ user.name, user.address.city });
} else {
const text = try result.errors().render(allocator, .{});
defer allocator.free(text);
std.debug.print("{s}", .{text});
}
}parse returns a ParseResult. A successful result holds the decoded value; a failed one holds an issue list and a null value. The input text is not referenced after parse returns.
Run it ​
Save the program as main.zig, add the module to your build.zig, and run:
bash
zig build runExpected output:
text
Ada in LondonBreak the document on purpose, for example by changing the postal code to "AB12", and the same program prints:
text
error[E004]: invalid length
$.address.postal_code
expected: exactly 5 characters
received: "AB12"Next steps ​
- Schemas explains the schema protocol and composition.
- Inferred Objects, Tuples & Intersections shows how to derive models and fixed tuples at compile time.
- Validation Types lists every built-in format and the complete string and number options.
- Date & Time covers calendar arithmetic, formatting and fixed-offset timestamps.
- Examples walks through nine complete programs with output.
