diff --git a/src/Item.zig b/src/Item.zig index 4beff6a..ab6f3ab 100644 --- a/src/Item.zig +++ b/src/Item.zig @@ -91,11 +91,12 @@ pub fn fromJson(jobj: json.Obj, allocator: std.mem.Allocator) !Self { // Try to assemble a Item object from a JSON string // An item could be just an id, just tags or both. - var opt_jtags = jobj.objectGet("tags") catch null; var tags: ?[]Tag = null; - if (opt_jtags) |*jtags| { + if (jobj.objectGet("tags") catch null) |*jtags| { defer jtags.deinit(); + + // Reserve space for slice of tags const len = @intCast(usize, jtags.objectLen()); tags = try allocator.alloc(Tag, len); @@ -111,8 +112,19 @@ pub fn fromJson(jobj: json.Obj, allocator: std.mem.Allocator) !Self { } } + var id: ?i64 = null; + + if (jobj.objectGet("id") catch null) |*jid| { + defer jid.deinit(); + + id = jid.getInt64(); + } + + // TODO: What should be done when both things are null? + // Return a null Obj or leave it as-is? + return Self{ - .id = null, + .id = id, .tags = tags, .allocator = allocator, }; diff --git a/src/json.zig b/src/json.zig index 45fa35e..72d6dfb 100644 --- a/src/json.zig +++ b/src/json.zig @@ -56,6 +56,10 @@ pub const Obj = struct { // TODO: Check type to not allow other types return std.mem.sliceTo(c.json_object_get_string(self.obj), 0); } + pub fn getInt64(self: Obj) i64 { + // TODO: Check ERRNO to see if there was an error + return c.json_object_get_int64(self.obj); + } pub fn deinit(self: *Obj) void { _ = c.json_object_put(self.obj);