0

I am trying to build a JSON object using the json-c library and I am using the C language. I would like to know the best way to add objects to an array in a loop.

What I have:

struct json_object * build_array(char *input_buffer) {
    struct json_object *res = json_object_new_array();
    while(//buffer has data I need) {
        struct json_object *obj1 = json_object_new_object();
        
        json_object_object_add(obj, "foo", json_object_new_string("foo"));
        json_object_object_add(obj, "bar", json_object_new_string("bar"));
        json_object_array_add(res, obj);
    
    }

    return res;
} 

Is there an issue that could be caused by declaring the object as a new object each iteration of the loop? If so, what is a better way of using a loop to add items to the array?

spiderwebdev
  • 75
  • 1
  • 8
  • That looks OK I would say. That said, I didn't work with json-c yet and don't know about resource management/reference counting in that library. From the examples I saw it should be fine. – Gerhardh Oct 12 '22 at 14:33

0 Answers0