--- layout: site.njk title: zul.fs.readJson ---

Reads and parses a JSON file.

{% highlight zig %} // Parameters: // 1- The type to parse the JSON data into // 2- An allocator // 3- Absolute or relative path // 4- std.json.ParseOptions const managed_user = try zul.fs.readJson(User, allocator, "/tmp/data.json", .{}); // readJson returns a zul.Managed(T) // managed_user.value is valid until managed_user.deinit() is called defer managed_user.deinit(); const user = managed_user.value; {% endhighlight %}

comptime T: type

The type to parse to.

allocator: std.mem.Allocator

The allocator to use for any memory allocations needed to parse the JSON or create T.

path: []const u8

Absolute or relative path to the file.

opts: std.json.ParseOptions

Options that control the parsing. The allocate field will be forced to alloc_always.

On success, readJson(T, ...) returns a zul.Managed(T) which exposes a deinit() method as well as the the parsed value in the value: T field.

Parsing JSON and creating T likely requires memory allocations. These allocations are done within an std.heap.ArenaAllocator. Thus, the parsed value: T has a lifetime tied to the arena. When zul.Manage(T).deinit() is called, the arena is cleared and freed.

zul.Manage is a renamed std.json.Parsed(T) (I dislike the name std.json.Parsed(T) because it represents data and behavior that has nothing to with with JSON or parsing).