Search code examples
cjansson

How to extract keyless values from json array using jansson


I want to extract strings from a JSON that doesn't have the key descriptor in front of the values but where the values are simply separated by a '|'.

This is an example of the kind of input I have:

{"data":["this|is|an|","example|thank|","you|very|much|"]}

Note that on the documentation, the Jansson fuctions that i find helpful always have a key as argument (but my array only have strings without a key). If someone could help i will be very thankful.


Solution

  • For elements of an array you don't need any keys as you can access them via index.

    First you get the array itself as a json object:

    int result;
    json_t *data = NULL;
    result = json_unpack(json_p, "{s:o}", "data", &data);
    

    Then you can get the elements:

    int num_data = 0;
    if (data != NULL && json_is_array(data))
      num_data = json_array_size(data);
    
    for (int i=0; i<num_data; i++)
    {
       json_t *one_elem = json_array_get(data, i);
       // Do whatever has to be done...
    }