KeithSmith
KeithSmith

Reputation: 774

How to find a name in a name/value pair using cJSON

cJSON provides a function

CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)

I created a test function

#include "cJSON.h"
const char *jsonstring = "{\"b\": {\"b1\":\"2b\"}}";

void jsontest(void)
{
  cJSON *cJSON_data = cJSON_Parse(jsonstring);
  char *buffer = cJSON_Print(cJSON_data);
  printf("JSON_String:%s\r\n",buffer);
  cJSON *bfound = cJSON_GetObjectItemCaseSensitive(cJSON_data,"b1");
  printf("bfound: 0x%08x\n",(char*)bfound);
  free(cJSON_data);
  free(buffer);
}

The output is

JSON_String:{
    "b":    {
        "b1":   "2b"
    }
}

bfound: 0x00000000

`

If I use this string,

const char *jsonteststr1 = "{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"}";

GetObjectItemCaseSensitive() will find "a", "b", and "c".

GetObjectItemCaseSensitive() does not seem to recurse.

Am I doing something wrong? Do I not understand how to use GetObjectItem()?

I am using version 1.7.12

Upvotes: 0

Views: 1498

Answers (1)

Alan Wang
Alan Wang

Reputation: 41

cJSON_GetObjectItemCaseSensitive(object, string) can only get the the direct child and child's siblings of object, we can't find the child's child node through it.

if you want to get the value of 2b, then you should:

#include "cJSON.h"
const char *jsonstring = "{\"b\": {\"b1\":\"2b\"}}";

void jsontest(void)
{
  cJSON *cJSON_data = cJSON_Parse(jsonstring);
  char *buffer = cJSON_Print(cJSON_data);
  printf("JSON_String:%s\r\n",buffer);
  cJSON *bfound = cJSON_GetObjectItemCaseSensitive(cJSON_data,"b");  // cJSON_data only has a child which named "b"
  cJSON *b1_found = cJSON_GetObjectItemCaseSensitive(bfound, "b1");  // key/value: <b1, 2b> is in b1_found, not bfound
  printf("b1_found: 0x%08x\n",(char*)b1_found);
  printf("bfound: 0x%08x\n",(char*)bfound);

  cJSON_Delete(cJSON_data);  // you should use cJSON_Delete to free the json item.
  free(buffer);
}

Upvotes: 2

Related Questions