Assuming the following JSON object, an array of [epoch, value] arrays:
[ [0,1], [1912312314,2], [1912312857,5] ]
What's the correct way to remove an element of the array ? The idea is to remove the one with an epoch alder than a given value. I use json-c 0.11.
I tried :
json_object *jsonHeatmapObj;
jsonHeatmapObj = json_tokener_parse ( "[ [0,1], [1912312314,2], [1912312857,5] ]" );
for ( int idx=0 ; idx < json_object_array_length(jsonHeatmapObj) ; idx++ ) {
json_object *curJsonHeatpointObj = json_object_array_get_idx ( jsonHeatmapObj , idx );
int x = json_object_get_int ( json_object_array_get_idx ( curJsonHeatpointObj , 0 ) );
if ( x < time(NULL) - 10 ) {
json_object_put ( curJsonHeatpointObj );
}
printf("\t[%d]=%s\n", idx, json_object_to_json_string(jsonHeatmapObj));
}
This fails (SIGSEGV) when calling json_object_to_json_string() with the adjusted object.
Thank you
I think there are two separate issues with that code: one is that it is using json_object_put
as if json_object_array_get_idx
had removed the element it returns from the original array (something that is not at all clear from the API documentation), and second that it uses time(NULL)
as if it was returning an integer, but it is returning a time_t
struct.
The first one can be solved by creating a new JSON array and only including items in it if the condition is met. Here I am avoiding the second issue by using a time that is set to the largest value in the array:
struct json_object *newHeatMap = json_object_new_array();
for ( int idx=0 ; idx < json_object_array_length(jsonHeatmapObj) ; idx++ ) {
json_object *curJsonHeatpointObj = json_object_array_get_idx ( jsonHeatmapObj , idx );
int x = json_object_get_int ( json_object_array_get_idx ( curJsonHeatpointObj , 0 ) );
if ( x < 1912312857 ) {
json_object_array_add(newHeatMap, curJsonHeatpointObj);
}
printf("\t[%d]=%s\n", idx, json_object_to_json_string(newHeatMap));
}
I get the following results, which I hope are what you intend to see:
$ gcc -I/opt/local/include -L/opt/local/lib/ -ljson-c main.c && ./a.out example.json
[0]=[ [ 0, 1 ] ]
[1]=[ [ 0, 1 ], [ 1912312314, 2 ] ]
[2]=[ [ 0, 1 ], [ 1912312314, 2 ] ]
The second problem has already been answered for instance here on SO
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments