Skip to content

Document

The Document struct represents a parsed ZON document and provides methods for reading, writing, searching, and saving.

Initialization

Create Empty Document

zig
var doc = zon.create(allocator);
defer doc.deinit();

Open From File

zig
var doc = try zon.open(allocator, "config.zon");
defer doc.deinit();

Load or Create

zig
var doc = try zon.loadOrCreate(allocator, "settings.zon", ".{ .theme = .dark }");
defer doc.deinit();

Parse From String

zig
var doc = try zon.parse(allocator, source);
defer doc.deinit();

Getters

All getters return null for missing paths or type mismatches.

MethodReturn TypeDescription
getString(path)?[]const u8Get string value
getStr(path)?[]const u8Alias for getString
getIdentifier(path)?[]const u8Get identifier value
getBool(path)?boolGet boolean value
getInt(path)?i64Get integer value
getNum(path)?i64Alias for getInt
getInteger(path)?i64Alias for getInt
getFloat(path)?f64Get float value
getDecimal(path)?f64Alias for getFloat
getNumber(path)?f64Alias for getFloat
getValue(path)?*const ValueGet raw Value
isNull(path)boolCheck if value is null
isIdentifier(path)boolCheck if value is identifier
exists(path)boolCheck if path exists
has(path)boolAlias for exists
contains(path)boolAlias for exists
getType(path)?[]const u8Get base type name
getTypeName(path)?[]const u8Get precise type name
isNan(path)boolCheck if value is NaN
isInf(path)boolCheck if value is Inf
getUint(path)?u64Get unsigned integer (u64)
toBool(path)boolCoerce value to boolean

Setters

All setters auto-create intermediate objects.

MethodDescription
setString(path, val)Set string value
setStr(path, val)Alias for setString
putStr(path, val)Alias for setString
setIdentifier(p, v)Set identifier (.value)
setBool(p, v)Set boolean value
setInt(p, v)Set integer value
putInt(p, v)Alias for setInt
setNum(p, v)Alias for setInt
setFloat(p, v)Set float value
setNumber(p, v)Alias for setFloat
setNull(path)Set value to null
putNull(path)Alias for setNull
clearPath(path)Alias for setNull
setObject(path)Create empty object
setArray(path)Create empty array
setValue(path, v)Set raw Value
put(path, v)Alias for setValue

Modification

MethodReturnDescription
delete(path)boolDelete key, returns true if existed
remove(path)boolAlias for delete
rename(o, n)!boolRename key/path
move(o, n)!boolAlias for rename
copy(s, d)!boolDuplicate path
clear()voidClear all data
count()usizeNumber of root keys
size()usizeAlias for count
len()usizeAlias for count
keys()![][]const u8All root keys (caller frees)
isEmpty()boolCheck if document is empty

Array Operations

MethodReturnDescription
arrayLen(path)?usizeGet array length
getArrayElement(path, index)?*const ValueGet element at index
getArrayString(path, index)?[]const u8Get string at index
getArrayInt(path, index)?i64Get integer at index
getArrayBool(path, index)?boolGet boolean at index
appendToArray(path, string)!voidAppend string
appendIntToArray(path, int)!voidAppend integer
appendFloatToArray(path, float)!voidAppend float
appendBoolToArray(path, bool)!voidAppend boolean
removeFromArray(path, index)boolRemove item at index
insertStringIntoArray(path, idx, val)!voidInsert string
insertIntIntoArray(path, idx, val)!voidInsert integer
indexOf(path, value)?usizeFind string index
countAt(path)usizeCount items at path

Find & Replace

MethodReturnDescription
findString(needle)![][]const u8Find paths containing needle
findExact(needle)![][]const u8Find paths with exact match
replaceAll(find, replace)!usizeReplace all, returns count
replaceFirst(find, replace)!boolReplace first
replaceLast(find, replace)!boolReplace last
find(key)?*ValueRecursive key search
findAll(key)![][]const u8Deep key search (paths)
rename(old, new)!boolRename key/path
move(old, new)!boolAlias for rename
copy(src, dst)!boolDuplicate path
diff(other)![]const []u8Deep recursive diff
flatten()!DocumentConvert to flat map

Integrity & Size

MethodReturnDescription
hash()u64Stable 64-bit content hash
checksum(algo, &out)voidGenerate crypto digest
byteSize()!usizeSize in bytes when formatted
compactSize()!usizeSize in bytes when compact

Merge & Clone

MethodReturnDescription
merge(other)!voidShallow merge document
mergeRecursive(other)!voidRecursive (deep) merge
clone()!DocumentCreate deep copy
eql(other)boolDeep equality check

Convenience Methods

MethodReturnDescription
getStringOr(path, default)[]const u8Get string or fallback
getIntOr(path, default)i64Get integer or fallback
getBoolOr(path, default)boolGet boolean or fallback
getFloatOr(path, default)f64Get float or fallback
getTypeName(path)?[]const u8Get precise type name

Output

MethodReturnDescription
save()!voidSave to original path
saveAs(path)!voidSave to specified path
saveAsAtomic(path)!voidAtomically write file (write tmp + rename)
saveWithBackup(ext)!voidSave and move previous file to <path><ext>
saveIfChanged()!boolSave only if contents changed (returns true if written)
toString()![]u84-space indent (caller frees)
toCompactString()![]u8No indentation
toPrettyString(indent)![]u8Custom indentation

Utilities (Top-level)

MethodReturnDescription
zon.validate(src)boolCheck if ZON is valid
zon.validateFile(path)boolCheck if file is valid ZON
zon.format(src)![]u8Re-format ZON source
zon.formatFile(path)!voidRe-format ZON file in-place
zon.deleteFile(path)!voidDelete a file
zon.removeFile(path)!voidAlias for deleteFile
zon.copyFile(src,dst)!voidCopy a file
zon.moveFile(old,new)!voidRename/Move a file
zon.renameFile(old,new)!voidAlias for moveFile
zon.movePathInFile()!voidMove key inside ZON file
zon.copyPathInFile()!voidCopy key inside ZON file
zon.isZonValid(src)boolAlias for validate
zon.isZonFileValid(p)boolAlias for validateFile

Object & Array Access

MethodReturnDescription
getObject(path)?*Value.ObjectGet object reference
getArray(path)?*Value.ArrayGet array reference

Cleanup

zig
doc.close();
// or
doc.deinit();

Resource Management

Always call close() or deinit() when done with a document to prevent memory leaks.

Complete Example

zig
const std = @import("std");
const zon = @import("zon");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    zon.disableUpdateCheck();

    var doc = zon.create(allocator);
    defer doc.deinit();

    // Set values
    try doc.setString("name", "myapp");
    try doc.setString("version", "1.0.0");
    try doc.setInt("port", 8080);

    // Nested paths
    try doc.setString("config.host", "localhost");
    try doc.setInt("config.timeout", 30);

    // Arrays
    try doc.setArray("paths");
    try doc.appendToArray("paths", "src");
    try doc.appendToArray("paths", "lib");

    // Read values
    const name = doc.getString("name").?;
    const port = doc.getInt("port").?;
    const path_count = doc.arrayLen("paths").?;

    std.debug.print("{s} on port {d}, {d} paths\n", .{name, port, path_count});

    // Check properties
    if (doc.exists("config.host")) {
        std.debug.print("Host: {s}\n", .{doc.getString("config.host").?});
    }

    if (doc.isEmpty()) {
        std.debug.print("Document is empty\n", .{});
    }

    // Find and replace
    const count = try doc.replaceAll("localhost", "production.example.com");
    std.debug.print("Replaced {d} values\n", .{count});

    // Clone
    var backup = try doc.clone();
    defer backup.deinit();

    // Output
    const output = try doc.toString();
    defer allocator.free(output);
    std.debug.print("{s}\n", .{output});

    // Save
    try doc.saveAs("config.zon");
}

Released under the MIT License.