Using cJSON to read in a JSON array

Document mentions about parse_object().

I think this is what you need to do.

void parse_object(cJSON *root)
{
  cJSON* name = NULL;
  cJSON* index = NULL;
  cJSON* optional = NULL;

  int i;

  cJSON *item = cJSON_GetObjectItem(items,"items");
  for (i = 0 ; i < cJSON_GetArraySize(item) ; i++)
  {
     cJSON * subitem = cJSON_GetArrayItem(item, i);
     name = cJSON_GetObjectItem(subitem, "name");
     index = cJSON_GetObjectItem(subitem, "index");
     optional = cJSON_GetObjectItem(subitem, "optional"); 
  }
}

Call this function as

request_json = cJSON_Parse(request_body);
parse_object(request_json);

If you want to run slightly faster, this is what the code looks like:

void parse_array(cJSON *array)
{
  cJSON *item = array ? array->child : 0;
  while (item)
  {
     cJSON *name = cJSON_GetObjectItem(item, "name");
     cJSON *index = cJSON_GetObjectItem(item, "index");
     cJSON *optional = cJSON_GetObjectItem(item, "optional"); 

     item=item->next;
  }
}

This avoids the O(n^2) cost that RBerteig correctly points out.

Call with:

parse_array(cJSON_GetObjectItem(cJSON_Parse(request_body),"items"));

Tags:

C

Json

Cjson