0

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

KeithSmith
  • 774
  • 2
  • 8
  • 26

1 Answers1

2

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);
}
Alan Wang
  • 41
  • 5
  • hi, there is no method to retrieve a value on a provided key ? In json, keys are supposed to be unique, so the method does make sense to me. – le-cardinal Feb 10 '23 at 16:21