artificer/api/json_utils.zig

81 lines
1.9 KiB
Zig

const std = @import("std");
const Allocator = std.mem.Allocator;
const json = std.json;
pub fn getInteger(object: json.ObjectMap, name: []const u8) ?i64 {
const value = object.get(name);
if (value == null) {
return null;
}
if (value.? != json.Value.integer) {
return null;
}
return value.?.integer;
}
pub fn getIntegerRequired(object: json.ObjectMap, name: []const u8) !i64 {
return getInteger(object, name) orelse return error.MissingProperty;
}
pub fn asObject(value: json.Value) ?json.ObjectMap {
if (value != json.Value.object) {
return null;
}
return value.object;
}
pub fn asArray(value: json.Value) ?json.Array {
if (value != json.Value.array) {
return null;
}
return value.array;
}
pub fn getObject(object: json.ObjectMap, name: []const u8) ?json.ObjectMap {
const value = object.get(name);
if (value == null) {
return null;
}
return asObject(value.?);
}
pub fn getArray(object: json.ObjectMap, name: []const u8) ?json.Array {
const value = object.get(name);
if (value == null) {
return null;
}
return asArray(value.?);
}
pub fn getString(object: json.ObjectMap, name: []const u8) ?[]const u8 {
const value = object.get(name);
if (value == null) {
return null;
}
if (value.? != json.Value.string) {
return null;
}
return value.?.string;
}
pub fn getStringRequired(object: json.ObjectMap, name: []const u8) ![]const u8 {
return getString(object, name) orelse return error.MissingProperty;
}
pub fn dupeString(allocator: Allocator, object: json.ObjectMap, name: []const u8) !?[]u8 {
const str = getString(object, name) orelse return null;
return try allocator.dupe(u8, str);
}
pub fn dupeStringRequired(allocator: Allocator, object: json.ObjectMap, name: []const u8) ![]u8 {
return (try dupeString(allocator, object, name)) orelse return error.MissingProperty;
}