Using cJSON to read in a JSON array

ぐ巨炮叔叔 提交于 2019-12-09 04:20:44

问题


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

"items": 
[
    {
        "name": "command",
        "index": "X",
        "optional": "0"
    },
    {
        "name": "status",
        "index": "X",
        "optional": "0"
    }
]

From reading his documentation, I found ways to read in individual Objects, but nothing regarding Arrays, and I wasn't able to surmise how to do it from the examples given.

Here's what I'm trying:

cJSON* request_json = NULL;
cJSON* items = cJSON_CreateArray();
cJSON* name = NULL;
cJSON* index = NULL;
cJSON* optional = NULL;

request_json = cJSON_Parse(request_body);

items = cJSON_GetObjectItem(request_json, "items");

name = cJSON_GetObjectItem(items, "name");
index = cJSON_GetObjectItem(items, "index");
optional = cJSON_GetObjectItem(items, "optional");

I know this is wrong, and not just because it's not working, but I can't figure out how to make it right.

Obviously I'm going to need to loop the process of reading in all of the entries for each index of the array. I have no idea how I'm going to do that though, because I don't know where I should be using the indexes in this code, or if it is even the right start. There is a cJSON_GetArrayItem(), but it takes only a number (presumably an index) and no string to indicate which field it wants.


回答1:


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



回答2:


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



回答3:


IMHO, this is one example of a case where you should burst the library's encapsulation and work directly with it's object data structure. cJSON.h defines the core object as the following struct:

/* The cJSON structure: */
typedef struct cJSON {
    struct cJSON *next,*prev;   /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
    struct cJSON *child;        /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */

    int type;                   /* The type of the item, as above. */

    char *valuestring;          /* The item's string, if type==cJSON_String */
    int valueint;               /* The item's number, if type==cJSON_Number */
    double valuedouble;         /* The item's number, if type==cJSON_Number */

    char *string;               /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;

(One could quibble with some of the naming choices the author made, of course. But good naming is hard.)

The key thing to note is that both JSON Objects and JSON Arrays have a non-null child field, which points to a doubly-linked list of their children. Children of JSON Objects also have non-null string fields which contains the field name associated with that child.

So, to generically iterate over the JSON Array ja in O(n) time, calling a function for each element, you write something like this:

cJSON_ForEachItem(cJSON *ja, int (*f)(cJSON *ja, int i, cJSON *jchild)) 
{
    cJSON *jchild;
    int i;
    for (jchild=ja->child, i=0; jchild; jchild=jchild->next, ++i) {
        // do something here with the ith child...
        if (f(ja, i, jchild))
            break;
    }
}

Since Objects and Arrays only differ internally in the presence of names for each child item, that function will also iterate the fields of an object. The callback can tell because ja->type will be either cJSON_Array or cJSON_Object, and jchild->string will be non-null for Objects as well.

Doing the same iteration by calling cJSON_GetArraySize() and using cJSON_GetArrayItem() will be order O(n^2) because it has to traverse the linked list each time to locate the nth item.

Arguably, cJSON should include some generic ForEach functions, but that might represent the beginning of a significant amount of scope-creep away from it's professed original goal of being "the dumbest possible parser that you can get your job done with".




回答4:


My guess (not having read the spec, and being a bit rusty with C):

request_json = cJSON_Parse(request_body);

items = cJSON_GetObjectItem(request_json, "items");
for (int i = 0; i < max; i++) {  // Presumably "max" can be derived from "items" somehow

    cJSON* item = cJSON_GetArrayItem(items, i);

    name = cJSON_GetObjectItem(item, "name");
    index = cJSON_GetObjectItem(item, "index");
    optional = cJSON_GetObjectItem(item, "optional");

    // Stash above info somewhere
}


来源:https://stackoverflow.com/questions/16900874/using-cjson-to-read-in-a-json-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!