Nealon Nealon - 6 months ago 54
JSON Question

Using cJSON to read in a JSON array

First off, this is a very broad question, and it might come across as me asking for the community to write my code for me. That is not my intent, but I am so lost, I don't know how to give enough information.

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.

Please ask for more information as needed, and I will make edits to the question. I in no way expect an answer right away. Thank you.

Answer

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