Search code examples
carraysjsonjson-c

Append json_object_arrays in C using jsonc library


I am new to the C language. I need to append two json_object arrays created with the json-c library. This is my code:

struct json_object *obj1,*array1,*array2,*array3;

obj1 = json_object_new_object();    

array1 = json_object_new_array();
json_object_array_add(array1, json_object_new_int(1));
json_object_array_add(array1, json_object_new_int(2));
json_object_array_add(array1, json_object_new_int(3));  

json_object_object_add(obj1, "array1", array1);

array2 = json_object_new_array();
json_object_array_add(array2, json_object_new_int(4));
json_object_array_add(array2, json_object_new_int(5));
json_object_array_add(array2, json_object_new_int(6));  

json_object_object_add(obj1, "array2", array2);

json_object_object_add(obj1, "array3", array1+array2);

But I got the following error:

error: invalid operands to binary + (have ‘struct json_object *’ and ‘struct json_object *’) json_object_object_add(obj1, "array3", array1+array2);

Is this not possible? I need output like this:

{
   "array1:[1,2,3],
   "array2":[4,5,6],
   "array3":[1,2,3,4,5,6]
}

Or is it possible to add a normal C integer array to Json, like this

int32_t smp[100]={0};

smp[0] = 1;
smp[1] = 2;
smp[2] = 3;
smp[3] = 4;
smp[4] = 5;
smp[5] = 6;

json_object_object_add(obj1, "array3", smp);

Solution

  • As far as I know, there is no "built-in" function in json-c to concatenate two arrays, but you can easily create one:

    struct json_object * json_object_array_concat (struct json_object *array1,
                                                   struct json_object *array2) {
        struct json_object *array3 = json_object_new_array();
        if (!array3) {
            return NULL;
        }
        int i,
            size1 = json_object_array_length(array1),
            size2 = json_object_array_length(array2);
        for (i = 0; i < size1; ++i) {
            json_object_array_add(array3, json_object_array_get_idx(array1, i));
        }
        for (i = 0; i < size2; ++i) {
            json_object_array_add(array3, json_object_array_get_idx(array2, i));
        }
        return array3;
    }
    

    Then to use it:

    array3 = json_object_array_concat(array1, array2);
    

    If you only want to append array2 to array1:

    struct json_object * json_object_array_append (struct json_object *array1,
                                                   struct json_object *array2) {
        int i,
            size2 = json_object_array_length(array2);
        for (i = 0; i < size2; ++i) {
            json_object_array_add(array1, json_object_array_get_idx(array2, i));
        }
        return array1;
    }