Using cJSON to read in a JSON array

后端 未结 4 721
醉梦人生
醉梦人生 2021-02-04 09:42

I am attempting to use the cJSON library, written by Dave Gamble, to read in the following JSON array:

\"items\": 
[
    {
        \"name\": \"command\",
                


        
4条回答
  •  野性不改
    2021-02-04 10:03

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

提交回复
热议问题