I try to parse a JSON file using yajl 2.0.4 (using yajl_tree.h) but I have some problems to detect whether the found value is an array or not (even if I use YAJL_IS_ARRAY, it seems that the type field is not set.
Here is my JSON file :
{
"equipment": [
{
"name": "mynode",
"type": "node",
"attribute": [
{
"name": "cpu_available",
"value": "8"
},
{
"name": "memory_available",
"value": "24"
}
]
}
]
}
Here is my code :
const char *path[] = { "equipment", (const char *) 0 };
yajl_val v = yajl_tree_get( node, path, yajl_t_array );
if ( v && YAJL_IS_ARRAY( v ) ) {
for ( i = 0; i < v->u.array.len; i++ ) {
yajl_val obj = v->u.array.values[i];
if( obj && YAJL_IS_ARRAY(obj)) {
for ( j = 0; j < obj->u.object.len; j++ ) {
yajl_val obj2 = obj->u.array.values[ j ];
if(obj2 && YAJL_IS_ARRAY(obj2)) {
for ( k = 0; k < obj2->u.array.len; k++ ) {
yajl_val obj3 = obj->u.array.values[ k ];
const char * key3 = obj3->u.object.keys[ k ];
yajl_val val3 = obj3->u.object.values[ k ];
printf( " %s : %s \n", key3, val3->u.string );
}
}
else {
const char * key2 = obj->u.object.keys[ j ];
yajl_val val2 = obj->u.object.values[ j ];
printf( " %s : %s \n", key2, val2->u.string );
}
}
}
else {
const char * key = obj->u.object.keys[ i ];
yajl_val val = obj->u.object.values[ i ];
printf( " %s : %s ", key, val->u.string );
}
}
}
When I use this code I never enter the YAJL_IS_ARRAY even if the value is an array, for example attribute. So I was wondering if YAJL_IS_ARRAY is not correct to get an array, what must be used ? Moreover, is it normal that the type of my objects (obj, obj2...) have no correct types ? What mistake did I do ?
Thanks in advance for your help. :)
Your JSON isn't an array. It's a dictionary with a key "equipment", and the value of "equipment" is an array. In this case, an array containing a single dictionary.