0

I am trying to parse an array within a JSON file, like so

{
    "val": [5,6]
}

using the following code, adapted from the parse_config.c included with the library,

char errbuf[1024];
yajl_val node;

long length;
char *file_data = read_file(&length, "conf.json");

node = yajl_tree_parse((const char *) file_data, errbuf, sizeof(errbuf));

const char *path[] = {"val", (const char *) 0};
yajl_val v = yajl_tree_get(node, path, yajl_t_number);

if (v)
    printf("Node found.\n");
else
    printf("Can't find node %s\n", path[0]);

yajl_tree_free(node);
free(file_data);

This method is successful for a single value, e.g.

{
    "val": 5
}

(by successful I mean that v is populated and Node found. is printed) but not for the array. What do I need to do differently for the array to be parsed?

Thanks.

Sam
  • 222
  • 2
  • 12

1 Answers1

0
  • You can use YAJL_IS_ARRAY to check v is array true or false. If v is an array,it will return true. If v is not an array, it will return false.
  • Next, You can use this code to parse it:

    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
        if(YAJL_IS_DOUBLE(obj)){
                printf( "%s/%f ", key, obj->u.number.d );
        }
     }
    
  • For details, You can see here: Parse complex JSON sub objects in C with YAJL
tuan ly
  • 2,714
  • 1
  • 7
  • 6