1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
//! JSON path helpers
//!
//! simplifies navigating nested json structures.
//! eliminates the verbose nested if-checks.
//!
//! two approaches:
//! - borrowed lookups: getString(value, "embed.external.uri") accepts literal or runtime paths
//! - typed decoding: extractAt(T, alloc, value, .{"embed", "external"}) decodes a subtree into T
//!
//! getters do not allocate; keep the source JSON alive while using their results.
//! extractAt validates at runtime and may allocate, including copies of string fields.
//! use an arena for extraction allocations, including partial results on failure.
//!
//! debug logging:
//! enable with `pub const std_options = .{ .log_scope_levels = &.{.{ .scope = .zat, .level = .debug }} };`
const std = @import("std");
const log = std.log.scoped(.zat);
/// navigate a json value by dot-separated path
/// returns null if any segment is missing or wrong type
/// numeric segments index arrays; literal keys containing dots require ObjectMap.get
/// returned values borrow the source JSON's storage
pub fn getPath(value: std.json.Value, path: []const u8) ?std.json.Value {
var current = value;
var it = std.mem.splitScalar(u8, path, '.');
while (it.next()) |segment| {
switch (current) {
.object => |obj| {
current = obj.get(segment) orelse return null;
},
.array => |arr| {
const idx = std.fmt.parseInt(usize, segment, 10) catch return null;
if (idx >= arr.items.len) return null;
current = arr.items[idx];
},
else => return null,
}
}
return current;
}
/// get a string at path
pub fn getString(value: std.json.Value, path: []const u8) ?[]const u8 {
const v = getPath(value, path) orelse return null;
return switch (v) {
.string => |s| s,
else => null,
};
}
/// get an integer at path
pub fn getInt(value: std.json.Value, path: []const u8) ?i64 {
const v = getPath(value, path) orelse return null;
return switch (v) {
.integer => |i| i,
else => null,
};
}
/// get a float at path
pub fn getFloat(value: std.json.Value, path: []const u8) ?f64 {
const v = getPath(value, path) orelse return null;
return switch (v) {
.float => |f| f,
.integer => |i| @floatFromInt(i),
else => null,
};
}
/// get a bool at path
pub fn getBool(value: std.json.Value, path: []const u8) ?bool {
const v = getPath(value, path) orelse return null;
return switch (v) {
.bool => |b| b,
else => null,
};
}
/// get an array at path
pub fn getArray(value: std.json.Value, path: []const u8) ?[]std.json.Value {
const v = getPath(value, path) orelse return null;
return switch (v) {
.array => |a| a.items,
else => null,
};
}
/// get an object at path
pub fn getObject(value: std.json.Value, path: []const u8) ?std.json.ObjectMap {
const v = getPath(value, path) orelse return null;
return switch (v) {
.object => |o| o,
else => null,
};
}
// === comptime path extraction ===
/// extract a typed struct from a nested path
/// the comptime tuple selects object keys; an empty tuple selects the root
/// decodes at runtime with std.json.parseFromValueLeaky, ignoring unknown fields
/// string and slice fields allocate; the caller manages allocations even on failure
/// prefer an arena when decoding; struct defaults apply only to absent fields
///
/// on failure, logs diagnostic info when debug logging is enabled for .zat scope
pub fn extractAt(
comptime T: type,
allocator: std.mem.Allocator,
value: std.json.Value,
comptime path: anytype,
) std.json.ParseFromValueError!T {
var current = value;
inline for (path) |segment| {
current = switch (current) {
.object => |obj| obj.get(segment) orelse {
log.debug("extractAt: missing field \"{s}\" in path {any}, expected {s}", .{
segment,
path,
@typeName(T),
});
return error.MissingField;
},
else => {
log.debug("extractAt: expected object at \"{s}\" in path {any}, got {s}", .{
segment,
path,
@tagName(current),
});
return error.UnexpectedToken;
},
};
}
return std.json.parseFromValueLeaky(T, allocator, current, .{ .ignore_unknown_fields = true }) catch |err| {
log.debug("extractAt: parse failed for {s} at path {any}: {s} (json type: {s})", .{
@typeName(T),
path,
@errorName(err),
@tagName(current),
});
return err;
};
}
/// extract a typed value, returning null on any error, including allocation failure
/// has the same allocation ownership as extractAt, including on failure
pub fn extractAtOptional(
comptime T: type,
allocator: std.mem.Allocator,
value: std.json.Value,
comptime path: anytype,
) ?T {
return extractAt(T, allocator, value, path) catch null;
}
// === tests ===
test "getPath simple" {
const json_str =
\\{"name": "alice", "age": 30}
;
const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json_str, .{});
defer parsed.deinit();
try std.testing.expectEqualStrings("alice", getString(parsed.value, "name").?);
try std.testing.expectEqual(@as(i64, 30), getInt(parsed.value, "age").?);
}
test "getPath nested" {
const json_str =
\\{"embed": {"external": {"uri": "https://example.com"}}}
;
const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json_str, .{});
defer parsed.deinit();
try std.testing.expectEqualStrings("https://example.com", getString(parsed.value, "embed.external.uri").?);
}
test "getPath array index" {
const json_str =
\\{"items": ["a", "b", "c"]}
;
const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json_str, .{});
defer parsed.deinit();
try std.testing.expectEqualStrings("b", getString(parsed.value, "items.1").?);
}
test "getPath missing returns null" {
const json_str =
\\{"name": "alice"}
;
const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json_str, .{});
defer parsed.deinit();
try std.testing.expect(getString(parsed.value, "missing") == null);
try std.testing.expect(getString(parsed.value, "name.nested") == null);
}
test "getPath deeply nested real-world example" {
// the exact painful example from user feedback
const json_str =
\\{
\\ "embed": {
\\ "$type": "app.bsky.embed.external",
\\ "external": {
\\ "uri": "https://tangled.sh",
\\ "title": "Tangled",
\\ "description": "Git hosting on AT Protocol"
\\ }
\\ }
\\}
;
const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json_str, .{});
defer parsed.deinit();
// instead of 6 nested if-checks:
const uri = getString(parsed.value, "embed.external.uri");
try std.testing.expectEqualStrings("https://tangled.sh", uri.?);
const title = getString(parsed.value, "embed.external.title");
try std.testing.expectEqualStrings("Tangled", title.?);
}
// === comptime extraction tests ===
test "extractAt struct" {
const json_str =
\\{
\\ "embed": {
\\ "external": {
\\ "uri": "https://tangled.sh",
\\ "title": "Tangled"
\\ }
\\ }
\\}
;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const parsed = try std.json.parseFromSlice(std.json.Value, arena.allocator(), json_str, .{});
const External = struct {
uri: []const u8,
title: []const u8,
};
const ext = try extractAt(External, arena.allocator(), parsed.value, .{ "embed", "external" });
try std.testing.expectEqualStrings("https://tangled.sh", ext.uri);
try std.testing.expectEqualStrings("Tangled", ext.title);
}
test "extractAt with optional fields" {
const json_str =
\\{
\\ "user": {
\\ "name": "alice",
\\ "age": 30
\\ }
\\}
;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const parsed = try std.json.parseFromSlice(std.json.Value, arena.allocator(), json_str, .{});
const User = struct {
name: []const u8,
age: i64,
bio: ?[]const u8 = null,
};
const user = try extractAt(User, arena.allocator(), parsed.value, .{"user"});
try std.testing.expectEqualStrings("alice", user.name);
try std.testing.expectEqual(@as(i64, 30), user.age);
try std.testing.expect(user.bio == null);
}
test "extractAt empty path extracts root" {
const json_str =
\\{"name": "root", "value": 42}
;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const parsed = try std.json.parseFromSlice(std.json.Value, arena.allocator(), json_str, .{});
const Root = struct {
name: []const u8,
value: i64,
};
const root = try extractAt(Root, arena.allocator(), parsed.value, .{});
try std.testing.expectEqualStrings("root", root.name);
try std.testing.expectEqual(@as(i64, 42), root.value);
}
test "extractAtOptional returns null on missing path" {
const json_str =
\\{"exists": {"value": 1}}
;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const parsed = try std.json.parseFromSlice(std.json.Value, arena.allocator(), json_str, .{});
const Thing = struct { value: i64 };
const exists = extractAtOptional(Thing, arena.allocator(), parsed.value, .{"exists"});
try std.testing.expect(exists != null);
try std.testing.expectEqual(@as(i64, 1), exists.?.value);
const missing = extractAtOptional(Thing, arena.allocator(), parsed.value, .{"missing"});
try std.testing.expect(missing == null);
}
test "extractAt logs diagnostic on enum parse failure" {
// simulates the issue: unknown enum value from external API
const json_str =
\\{"op": {"action": "archive", "path": "app.bsky.feed.post/abc"}}
;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const parsed = try std.json.parseFromSlice(std.json.Value, arena.allocator(), json_str, .{});
const Action = enum { create, update, delete };
const Op = struct {
action: Action,
path: []const u8,
};
// "archive" is not a valid Action variant - this should fail
// with debug logging enabled, you'd see:
// debug(zat): extractAt: parse failed for json.Op at path { "op" }: InvalidEnumTag (json type: object)
const result = extractAtOptional(Op, arena.allocator(), parsed.value, .{"op"});
try std.testing.expect(result == null);
}
test "extractAt logs diagnostic on missing field" {
const json_str =
\\{"data": {"name": "test"}}
;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const parsed = try std.json.parseFromSlice(std.json.Value, arena.allocator(), json_str, .{});
const Thing = struct { value: i64 };
// path "data.missing" doesn't exist
// with debug logging enabled, you'd see:
// debug(zat): extractAt: missing field "missing" in path { "data", "missing" }, expected json.Thing
const result = extractAtOptional(Thing, arena.allocator(), parsed.value, .{ "data", "missing" });
try std.testing.expect(result == null);
}
test "extractAt ignores unknown fields" {
// real-world case: TAP messages have extra fields (live, rev, cid) that we don't need
const json_str =
\\{
\\ "record": {
\\ "live": true,
\\ "did": "did:plc:abc123",
\\ "rev": "3mbspmpaidl2a",
\\ "collection": "pub.leaflet.document",
\\ "rkey": "xyz789",
\\ "action": "create",
\\ "cid": "bafyreitest"
\\ }
\\}
;
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const parsed = try std.json.parseFromSlice(std.json.Value, arena.allocator(), json_str, .{});
// only extract the fields we care about
const Record = struct {
collection: []const u8,
action: []const u8,
did: []const u8,
rkey: []const u8,
};
const rec = try extractAt(Record, arena.allocator(), parsed.value, .{"record"});
try std.testing.expectEqualStrings("pub.leaflet.document", rec.collection);
try std.testing.expectEqualStrings("create", rec.action);
try std.testing.expectEqualStrings("did:plc:abc123", rec.did);
try std.testing.expectEqualStrings("xyz789", rec.rkey);
}