0

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.

Tomás Rodrigues
  • 519
  • 2
  • 17

1 Answers1

2

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...
}
Gerhardh
  • 11,688
  • 4
  • 17
  • 39
  • thanks, this did the trick: json_string_value(json_array_get(arrayData, i))); I will accept your awser! :D btw, do you know some function in c that initializes multiple strings with the values between the pipes(|) ? – Tomás Rodrigues Nov 10 '17 at 17:21
  • Glad to help. Nope, you will have to do it manually in a loop. `strtok` will help to split the string, but allocation and assigning the tokens is your job. ;) – Gerhardh Nov 10 '17 at 17:24
  • Yeah, find it. I might use strsep, because strok looks obsolete in man pages. Thankz ;) – Tomás Rodrigues Nov 10 '17 at 17:33
  • 1
    Maybe, but `strtok` is a standard C function, while `strsep` is not. – Gerhardh Nov 10 '17 at 19:40