diff --git a/src/json.zig b/src/json.zig index 5dc0987..c297e77 100644 --- a/src/json.zig +++ b/src/json.zig @@ -28,7 +28,7 @@ pub const Obj = struct { pub fn newInt32(i: i32) Obj { return Obj{ .obj = c.json_object_new_int(i).? }; } - pub fn newInt64(i: i32) Obj { + pub fn newInt64(i: i64) Obj { return Obj{ .obj = c.json_object_new_int64(i).? }; } @@ -60,6 +60,20 @@ pub const Obj = struct { _ = c.json_object_object_add(self.obj, key, o); } + + /////////////////////////////////// + // ** Array functions ** + ///////////////////////////////// + + pub fn arrayAdd(self: *Obj, value: ?*Obj) void { + // TODO: Check type and error return + // TODO: Check if it can accept a null value + + // We need the json-c object or null, not the zig object + const o = if (value) |i| i.obj else null; + + _ = c.json_object_array_add(self.obj, o); + } }; // TODO: Create wrapper types that statically check and know there diff --git a/src/main.zig b/src/main.zig index 856a04c..3211745 100644 --- a/src/main.zig +++ b/src/main.zig @@ -15,7 +15,7 @@ pub fn main() !void { var tags = [2]Item.Tag{ .{ .name = "title", .value = "clean room" }, - .{ .name = "task", .value = "explosion preventer" }, + .{ .name = "task", .value = null }, }; var item = Item{ .id = null, .tags = &tags }; @@ -24,13 +24,19 @@ pub fn main() !void { var jobj = json.Obj.newObject(); + jobj.objectAdd("id", &json.Obj.newInt64(item.id.?)); + + var jtags = json.Obj.newObject(); + jobj.objectAdd("tags", &jtags); + + for (tags) |tag_i| { const jtag = if (tag_i.value) |value| &json.Obj.newString(value) else null; - jobj.objectAdd(tag_i.name, jtag); + jtags.objectAdd(tag_i.name, jtag); } defer jobj.deinit();