Two major categories of types exists in json-c, basic and composed.
Basic types
Namely boolean, int32, int64, double and string. All of those types have a new and a get method:
Note: don’t mix-up json_object_get_string() and json_object_to_json_string(),
json_object_get_string() should be used only to retrieve a string and the second only to print a whole json_object.
json_object_new_double_s() allows a much more accurate representation of the double.
json_object_new_string_len() create a new json_object from the supplied string, the buffer size for the string is of size len (with str[len+1] = '\0').
Composed types
Composed types are arrays and objects in json, and can contain every combination of types you can think of.
I never actually used json_object_get_array() and json_object_get_object(), it’s unlikely you will ever have to…
json_object_array_sort() don’t have much of documentation but it’s in fact a direct call to the qsort() system fonction (man 3 qsort).
json_object_object_foreach() is a handy foreach loop, key and val will be declared by the macro, you can name those variable as you please.
Warning: in version 0.10 of json-c json_object_object_add() doesn’t work properly if you try to overwrite the value of an existing key!
I strongly recommend you to use a newer version than 0.10. If you can’t, apply the patch from this commit github.com/json-c/json-c/commit/6988f53fcb05c13d99dd846494d79ea3bb3b1d4c.
Identify the type of a json object
As you might have noticed, every type is a json_object!
To differentiate types two functions are available:
json_type_null correspond to a NULL json_object pointer.
Example
After all those mind mind-numbing prototypes it’s example time. I didn’t wish to demonstrate how to use every single function, after all it’s almost identical from a boolean to any other basic type…