JSON to JSON Schema Generator — Zig source
Infer a draft-07 JSON Schema from any JSON document: scalar types, array item merging, all-keys-required objects and an optional strict mode. Runs locally in your browser with a shareable link.
This is the Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.
// json-to-schema — JSON instance → draft-07 JSON Schema inferrer. Zig port
// (canonical TS: src/lib/json-to-schema.ts; Go twin: cli/json-to-schema).
// Language: Zig 0.17 — std.json from the standard library (the Rust sibling
// embeds a hand-rolled parser instead, as Rust's stdlib has no JSON; the
// other Zig siblings predate the 0.15+ unmanaged-ArrayList API change).
// Given one JSON instance, infers a draft-07 style schema: the integer vs
// number split (2.0 is an integer — JSON has no int type), objects list every
// key as required with keys sorted, homogeneous arrays merge to a single item
// type, mixed arrays become a sorted `type` array (other keywords dropped),
// empty arrays carry no `items` key, and strict_objects adds
// "additionalProperties": false to every object schema. Empty or
// whitespace-only input yields empty output, not an error; parse failures
// surface the static message "Invalid JSON" (std.json reports no text).
// Output is a hand-rolled 2-space pretty print with JSON.stringify(schema,
// null, 2) parity. Pass an arena allocator — every byte the Result
// references lives in it; deinit the arena to free.
//
// Test: zig test zig.zig
const std = @import("std");
const Value = std.json.Value;
const DRAFT_07 = "http://json-schema.org/draft-07/schema#";
pub const Result = struct {
/// Pretty-printed schema, 2-space (JSON.stringify(schema, null, 2)).
/// Empty on error. Allocator-owned; caller frees.
output: []const u8 = "",
/// null when inference succeeded (TS: error: null).
err: ?[]const u8 = null,
};
/// Schema tree preserving JSON.stringify insertion order.
const Node = union(enum) {
obj: std.ArrayList(Entry),
arr: std.ArrayList(Node),
str: []const u8,
boolean: bool,
};
const Entry = struct { key: []const u8, val: Node };
fn strLess(_: void, a: []const u8, b: []const u8) bool {
return std.mem.order(u8, a, b) == .lt;
}
/// Six scalar kinds. Number.isInteger parity: an integral double (2.0, 1e2)
/// is an "integer" — JSON has no int type. std.json parses integral literals
/// as .integer; non-finite overflow (1e400, kept as .number_string) stays
/// "number", like JS Infinity.
fn scalarType(v: Value) []const u8 {
return switch (v) {
.array => "array",
.null => "null",
.bool => "boolean",
.integer => "integer",
.float => |f| if (std.math.isFinite(f) and @trunc(f) == f) "integer" else "number",
.number_string => "number",
.object => "object",
.string => "string",
};
}
fn scalarNode(a: std.mem.Allocator, kind: []const u8) std.mem.Allocator.Error!Node {
var obj: std.ArrayList(Entry) = .empty;
try obj.append(a, .{ .key = "type", .val = .{ .str = kind } });
return .{ .obj = obj };
}
/// Union of element kinds: one kind keeps it, else a sorted type list.
fn inferArrayItems(a: std.mem.Allocator, v: Value) std.mem.Allocator.Error!Node {
const items = v.array.items;
var kinds: std.ArrayList([]const u8) = .empty;
for (items) |el| {
const k = scalarType(el);
var dup = false;
for (kinds.items) |existing| {
if (std.mem.eql(u8, existing, k)) {
dup = true;
break;
}
}
if (!dup) try kinds.append(a, k);
}
std.mem.sort([]const u8, kinds.items, {}, strLess); // JS default sort parity
const type_node: Node = if (kinds.items.len == 1)
.{ .str = kinds.items[0] }
else blk: {
var arr: std.ArrayList(Node) = .empty;
for (kinds.items) |k| try arr.append(a, .{ .str = k });
break :blk .{ .arr = arr };
};
var obj: std.ArrayList(Entry) = .empty;
try obj.append(a, .{ .key = "type", .val = .{ .str = "array" } });
try obj.append(a, .{ .key = "items", .val = type_node });
return .{ .obj = obj };
}
fn infer(a: std.mem.Allocator, v: Value, strict: bool) std.mem.Allocator.Error!Node {
switch (v) {
.array => |items| {
if (items.items.len == 0) return scalarNode(a, "array"); // no `items` key
return inferArrayItems(a, v);
},
.object => |map| {
// duplicate keys are already collapsed (last wins) by std.json
var keys: std.ArrayList([]const u8) = .empty;
var it = map.iterator();
while (it.next()) |e| try keys.append(a, e.key_ptr.*);
// Byte order = code point order; JS sort is UTF-16 code-unit
// order — they differ only for astral keys.
std.mem.sort([]const u8, keys.items, {}, strLess);
var properties: std.ArrayList(Entry) = .empty;
for (keys.items) |k| {
const child = map.get(k).?;
try properties.append(a, .{ .key = k, .val = try infer(a, child, strict) });
}
var required: std.ArrayList(Node) = .empty;
for (keys.items) |k| try required.append(a, .{ .str = k });
var obj: std.ArrayList(Entry) = .empty;
try obj.append(a, .{ .key = "type", .val = .{ .str = "object" } });
try obj.append(a, .{ .key = "properties", .val = .{ .obj = properties } });
try obj.append(a, .{ .key = "required", .val = .{ .arr = required } });
if (strict) try obj.append(a, .{ .key = "additionalProperties", .val = .{ .boolean = false } });
return .{ .obj = obj };
},
else => return scalarNode(a, scalarType(v)),
}
}
// ---- 2-space pretty printer (JSON.stringify(v, null, 2) parity) ----
const HEX_DIGITS = "0123456789abcdef";
fn dumpString(a: std.mem.Allocator, out: *std.ArrayList(u8), s: []const u8) std.mem.Allocator.Error!void {
try out.appendSlice(a, "\"");
for (s) |c| {
switch (c) {
'"' => try out.appendSlice(a, "\\\""),
'\\' => try out.appendSlice(a, "\\\\"),
0x08 => try out.appendSlice(a, "\\b"),
0x0C => try out.appendSlice(a, "\\f"),
'\n' => try out.appendSlice(a, "\\n"),
'\r' => try out.appendSlice(a, "\\r"),
'\t' => try out.appendSlice(a, "\\t"),
else => {
if (c < 0x20) {
try out.appendSlice(a, "\\u"); // lowercase hex, like JS
try out.append(HEX_DIGITS[c >> 4]);
try out.append(HEX_DIGITS[c & 0xF]);
} else {
try out.append(c); // raw UTF-8 passes through, like JS
}
},
}
}
try out.appendSlice(a, "\"");
}
fn dump(a: std.mem.Allocator, out: *std.ArrayList(u8), node: *const Node, indent: usize) std.mem.Allocator.Error!void {
switch (node.*) {
.obj => |entries| {
if (entries.items.len == 0) {
try out.appendSlice(a, "{}");
return;
}
try out.appendSlice(a, "{\n");
for (entries.items, 0..) |e, i| {
if (i > 0) try out.appendSlice(a, ",\n");
try out.appendNTimes(a, ', indent * 2 + 2);
try dumpString(a, out, e.key);
try out.appendSlice(a, ": ");
try dump(a, out, &e.val, indent + 1);
}
try out.appendSlice(a, "\n");
try out.appendNTimes(a, ', indent * 2);
try out.appendSlice(a, "}");
},
.arr => |items| {
if (items.items.len == 0) {
try out.appendSlice(a, "[]");
return;
}
try out.appendSlice(a, "[\n");
for (items.items, 0..) |*el, i| {
if (i > 0) try out.appendSlice(a, ",\n");
try out.appendNTimes(a, ', indent * 2 + 2);
try dump(a, out, el, indent + 1);
}
try out.appendSlice(a, "\n");
try out.appendNTimes(a, ', indent * 2);
try out.appendSlice(a, "]");
},
.str => |s| try dumpString(a, out, s),
.boolean => |b| try out.appendSlice(a, if (b) "true" else "false"),
}
}
fn oom() Result {
return .{ .err = "Out of memory" };
}
/// Infer a draft-07 schema for the given JSON text, pretty-printed 2-space.
pub fn jsonToSchema(a: std.mem.Allocator, raw: []const u8, strict_objects: bool) Result {
const text = std.mem.trim(u8, raw, " \t\r\n\x0b\x0c");
if (text.len == 0) return .{}; // empty input is NOT an error
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
const arena_a = arena.allocator();
const parsed = std.json.parseFromSliceLeaky(Value, arena_a, text, .{}) catch {
return .{ .err = "Invalid JSON" };
};
// { $schema: DRAFT_07, ...infer(value) } — infer's entries follow $schema.
var root = Node{ .obj = .empty };
root.obj.append(arena_a, .{ .key = "$schema", .val = .{ .str = DRAFT_07 } }) catch return oom();
const inferred = infer(arena_a, parsed, strict_objects) catch return oom();
switch (inferred) {
.obj => |rest| root.obj.appendSlice(arena_a, rest.items) catch return oom(),
else => unreachable, // infer always returns an object node
}
var out: std.ArrayList(u8) = .empty;
dump(a, &out, &root, 0) catch return oom();
const owned = out.toOwnedSlice(a) catch return oom();
return .{ .output = owned };
}
pub fn main() !void {
// Small end-to-end demo so this file is runnable as a showcase.
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const res = jsonToSchema(arena.allocator(), "{\"b\": 1, \"a\": [1, \"x\"]}", true);
if (res.err) |e| {
std.debug.print("error: {s}\n", .{e});
return;
}
try std.fs.File.stdout().writeAll(res.output);
try std.fs.File.stdout().writeAll("\n");
}
test "json_to_schema inference parity" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const res = jsonToSchema(arena.allocator(), "{\"b\": 1, \"a\": [1, \"x\"]}", false);
try std.testing.expect(res.err == null);
try std.testing.expectEqualStrings(
\\{
\\ "$schema": "http://json-schema.org/draft-07/schema#",
\\ "type": "object",
\\ "properties": {
\\ "a": {
\\ "type": "array",
\\ "items": {
\\ "type": [
\\ "integer",
\\ "string"
\\ ]
\\ }
\\ },
\\ "b": {
\\ "type": "integer"
\\ }
\\ },
\\ "required": [
\\ "a",
\\ "b"
\\ ]
\\}
, res.output);
}
test "json_to_schema empty, invalid, scalar, empty array, strict" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
// Empty or whitespace-only input is NOT an error.
const empty = jsonToSchema(a, " \n\t ", false);
try std.testing.expectEqualStrings("", empty.output);
try std.testing.expect(empty.err == null);
// Parse failures carry the error string.
const bad = jsonToSchema(a, "{oops", false);
try std.testing.expectEqualStrings("", bad.output);
try std.testing.expectEqualStrings("Invalid JSON", bad.err.?);
// Top-level scalar.
const num = jsonToSchema(a, "42", false);
try std.testing.expectEqualStrings("{\n \"$schema\": \"" ++ DRAFT_07 ++ "\",\n \"type\": \"integer\"\n}", num.output);
// Empty array carries no `items` key.
const arr = jsonToSchema(a, "[]", false);
try std.testing.expectEqualStrings("{\n \"$schema\": \"" ++ DRAFT_07 ++ "\",\n \"type\": \"array\"\n}", arr.output);
// 2.0 is an integer — JSON has no int type.
const flt = jsonToSchema(a, "{\"v\": 2.0}", false);
try std.testing.expect(flt.err == null);
try std.testing.expect(std.mem.indexOf(u8, flt.output, "\"type\": \"integer\"") != null);
try std.testing.expect(std.mem.indexOf(u8, flt.output, "\"items\"") == null);
// strict_objects adds additionalProperties: false on every object schema.
const strict = jsonToSchema(a, "{\"a\": {\"b\": 1}}", true);
try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, strict.output, "\"additionalProperties\": false"));
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →