使用YAJL在C中解析复杂的JSON子对象

我有YAJL解析我在包含的示例中给出的简单元素没有问题。 (字符串,整数,数组……)

示例代码可以在这里找到: http : //lloyd.github.io/yajl/yajl-2.0.1/example_2parse_config_8c-example.html

但现在我有这种类型的JSON对象:

{ "cmd":2, "properties": [ { "idx":40, "val":8813.602692 }, { "idx":41, "val":960 }, { "idx":42, "val":2 }, { "idx":48, "val":9 } ] 

}

我可以检索命令(参见链接示例中使用的变量的定义):

 const char * path[] = {"cmd", (const char *) 0 }; yajl_val v = yajl_tree_get(ynode, path, yajl_t_number); if (v) *cmd = (commands)((int)YAJL_GET_INTEGER(v)); 

我可以使用以下命令获取属性数组的引用:

 int ar_sz; const char * path[] = {"properties", (const char *) 0 }; yajl_val v = yajl_tree_get(ynode, path, yajl_t_array); if (v) { ar_sz = v->u.array.len; } 

它给了我正确的数组大小,但我不知道如何从数组元素中检索嵌套元素idx和val。

非常感谢任何帮助

通过查看yajl_tree.h特别是yajl_val_s结构:

 { const char * path[] = { "properties", (const char *) 0 }; yajl_val v = yajl_tree_get( node, path, yajl_t_array ); if ( v && YAJL_IS_ARRAY( v ) ) { printf( "is array\n" ); // iterate over array elements, // it's an array so access array.len inside yajl_val_s.union size_t len = v->u.array.len; int i; for ( i = 0; i < len; ++i ) { // get ref to one object in array at a time yajl_val obj = v->u.array.values[ i ]; // object // iterate over values in object: pairs of (key,value) // u.object.len tells you number of elements size_t nelem = obj->u.object.len; int ii; for ( ii = 0; ii < nelem; ++ii ) { // key is just char * const char * key = obj->u.object.keys[ ii ]; // key // values is an array object yajl_val val = obj->u.object.values[ ii ]; // val // example: check if double, // could do more checks or switch on value ... if ( YAJL_IS_DOUBLE( val ) ) printf( "%s/%f ", key, val->u.number.d ); } printf( "\n" ); } } else { printf( "is not array\n" ); } } 

输出应该是这样的:

 is array idx/40.000000 val/8813.602692 idx/41.000000 val/960.000000 idx/42.000000 val/2.000000 idx/48.000000 val/9.000000