How to use the zon format

So im making a application, and i wanna use zon for it. i did see there was some stuff for it in the std but im unsure on how to use it.

thanks in advance

1 Like

Hello @maja
Welcome to ziggit :slight_smile:

To use zon, you need a master zig version (0.14.0-dev).

If the zon file is available at compile time you can @import the file.

To parse a zon file at runtime, you can use std.zon.parse.fromSlice where T is the zon type.

Example:

const std = @import("std");

test {
    const allocator = std.testing.allocator;

    const Foo = struct {
        bar: []const u8,
    };

    const zon = try std.zon.parse.fromSlice(
        Foo,
        allocator,
        ".{ .bar = \"AAA\" }",
        null,
        .{},
    );
    defer std.zon.parse.free(allocator, zon);

    try std.testing.expectEqualStrings("AAA", zon.bar);
}

For more information see the std.zon package documentation and zon pull request.

6 Likes

If the zon file is available at compile time you can @import the file.

I tried this approach, but it errors with expected type '[:0]const u8'. Could you give an example of this?

The closest thing I could find was this post, and reduced it to the below which works:

test "parse ZON file" {
    const allocator = std.testing.allocator;

    const Foo = struct {
        bar: []const u8,
    };

    const file = try std.fs.cwd().readFileAllocOptions(allocator, "foo.zon", 1024, null, std.mem.Alignment.@"1", 0);
    defer allocator.free(file);

    const parsed_struct = try std.zon.parse.fromSlice(Foo, allocator, file, null, .{});
    defer std.zon.parse.free(allocator, parsed_struct);

    try std.testing.expectEqualStrings("AAA", parsed_struct.bar);
}

where foo.zon is:

.{
    .bar = "AAA",
}

but wanted to know if there’s a better way ?


Edit: Sorry, its as simple as:

test "parse zon file" {
    const data = @import("foo.zon");
    try std.testing.expectEqualStrings("AAA", data.bar);
}