Parse complex JSON sub objects in C with YAJL

2019-07-04 22:08发布

问题:

I have YAJL parsing me simple elements like given in the included example without a problem. (strings, integers, arrays, ...)

The example code can be found here: http://lloyd.github.io/yajl/yajl-2.0.1/example_2parse_config_8c-example.html

but now I have this type of JSON object:

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

}

I can retrieve the command with (see the definitions of used variables in the linked example):

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));

And I can get the reference to the properties array using:

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;
  }

It gives me the correct array size, but I have no clue on how to retrieve the nested elements idx and val from the array elements.

Any help is very appreciated

回答1:

By looking at the yajl_tree.h specifically the yajl_val_s structure:

{
    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" ); }
}

Output should be something like:

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 


标签: c json yajl