mgtzm/src/json.zig

67 lines
2.0 KiB
Zig

const c = @cImport({
@cInclude("json.h");
});
const std = @import("std");
// NOTE: I try to be faithful to the original namings but also try to
// adapt some things to a more zig-ish style.
pub const Obj = struct {
obj: *c.json_object,
// TODO: Port type attribute to a zig enum and assign it upon creation
///////////////////////////////////
// ** JSON object types creation **
/////////////////////////////////
pub fn newObject() Obj {
return Obj{ .obj = c.json_object_new_object().? };
}
pub fn newArray() Obj {
return Obj{ .obj = c.json_object_new_array().? };
}
pub fn newString(s: [*c]const u8) Obj {
return Obj{ .obj = c.json_object_new_string(s).? };
}
pub const newInt = newInt32;
pub fn newInt32(i: i32) Obj {
return Obj{ .obj = c.json_object_new_int(i).? };
}
pub fn newInt64(i: i32) Obj {
return Obj{ .obj = c.json_object_new_int64(i).? };
}
pub fn deinit(self: *Obj) void {
_ = c.json_object_put(self.obj);
}
pub fn toString(self: *Obj) []const u8 {
// TODO: Allow passing of flags as an enum like the SDL2 binding
return std.mem.sliceTo(c.json_object_to_json_string(self.obj), 0);
}
///////////////////////////////////
// ** Object functions **
/////////////////////////////////
// TODO: Create an error for type checking.
pub fn objectGet(self: *Obj, key: [*c]const u8, value: **Obj) void {
// TODO: Check type and null return as errors
_ = c.json_object_object_get_ex(self.obj, key, value);
}
pub fn objectAdd(self: *Obj, key: [*c]const u8, value: ?*Obj) void {
// TODO: Check type and error return
// We need the json-c object or null, not the zig object
const o = if (value) |i| i.obj else null;
_ = c.json_object_object_add(self.obj, key, o);
}
};
// TODO: Create wrapper types that statically check and know there
// won't be any problems