-
-
Save johnLate/0bde3cf2cc2440889d2bdffa117ec2d6 to your computer and use it in GitHub Desktop.
playing with zig and json...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// tested with 0.6.0+58ee5f4e6 | |
const std = @import("std"); | |
const json = std.json; | |
const warn = std.debug.warn; | |
const J = struct { | |
pub fn lookup(json_value: std.json.Value, path: anytype) ?std.json.Value { | |
if (@typeInfo(@TypeOf(path)) != .Struct) { | |
@compileError("Expected struct argument (containing strings), found " ++ @typeName(@TypeOf(path))); | |
} | |
var value: ?std.json.Value = json_value; | |
comptime var i = 0; | |
inline while (i < path.len) : (i += 1) { | |
if (value == null) return null; | |
value = value.?.Object.get(path[i]); | |
} | |
return value; | |
} | |
pub fn lookup_old(json_value: std.json.Value, path: []const []const u8) ?std.json.Value { | |
var value: ?std.json.Value = json_value; | |
for (path) |dir| { | |
value = value.?.Object.get(dir).?; | |
} | |
return value; | |
} | |
}; | |
fn dumpValue(name: []const u8, value: ?std.json.Value) !void { | |
warn("{}: ", .{name}); | |
if (value == null) { | |
warn("{{not found}}", .{}); | |
} else { | |
try value.?.jsonStringify(.{}, std.io.getStdErr().outStream()); | |
} | |
warn("\n", .{}); | |
} | |
pub fn main() !void { | |
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); | |
defer arena.deinit(); | |
const allocator = &arena.allocator; | |
var parser = json.Parser.init(allocator, true); // (alloc, copy_strings) | |
defer parser.deinit(); | |
const raw_data = | |
\\{ "a": { "x": {"1": ["some", "data"] }}} | |
; | |
var tree = try parser.parse(raw_data); | |
defer tree.deinit(); | |
try dumpValue("root", tree.root); | |
var value1 = tree.root.Object.get("a").?.Object.get("x").?.Object.get("1"); | |
try dumpValue("(directly)", value1); | |
var value2 = J.lookup_old(tree.root, &[_][]const u8{ "a", "x", "1" }); | |
try dumpValue("(lookup_old)", value2); | |
var v = J.lookup(tree.root, .{ "a", "b", "1" }); | |
try dumpValue("v", v); | |
const user_query = "x"; | |
v = J.lookup(tree.root, .{ "a", user_query, "1" }); | |
try dumpValue("v", v); | |
v = J.lookup(tree.root, .{ ".", "x", "1" }); | |
try dumpValue("v", v); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: