Objects with underscore ("_") in their name not found
Having a simple Json (only one level-depth, 12 items),
- looking for the number of items with cJSON_GetArraySize returns 12 -> OK
- looking for an item with no underscore in the name using cJSON_HasObjectItem returns "true" -> OK
- looking for an item with underscore in the name using cJSON_HasObjectItem returns "false" -> WRONG
- Doing the same test with cJSON_GetObjectItem returns similar result.
Can you help please? Thanks.
Find a workaround using backslash auto escape underscore. Annoying
What version are you using? I tried both cJSON_HasObjectItem and cJSON_GetObjectItem and they worked fine for me without an escape. An underscore obviously should not require escaping. Can you show the specific code in question? I just used a simplistic test program. For example:
cJSON * const foo = cJSON_GetObjectItem(root, "foo");
if (foo)
printf("foo\n");
else
printf("no foo\n");
cJSON * const bar = cJSON_GetObjectItem(root, "bar_bah");
if (bar)
printf("bar_bah\n");
else
printf("no bar_bah\n");
My output was:
foo
bar_bah
I ran the same test using cJSON_HasObjectItem and observered the same results.
I use the last version available (downloaded yesterday).
Sample:
jToken = cJSON_GetObjectItem(json, "current\_power"); printf(">>%i<<\r\n", (jToken->type));
is working.
jToken = cJSON_GetObjectItem(json, "current_power"); printf(">>%i<<\r\n", (jToken->type));
hangs the program.
Json:
{"current_power":218}
Are you using the latest version in the master branch, or the latest official version, which is tagged 1.7.15? What platform are you running on? Where did you json variable come from? Where did the JSON string come from? It's not clear from your code fragments.
If you haven't tried already, I would suggest writing a simple, isolated code example to demonstrate whether or not the issue is there:
const char * jsonString = "{\"current_power\": 218}";
cJSON * json = cJSON_Parse(jsonString);
if (cJSON_HasObjectItem(json, "current_power"))
printf("It works\n");
else
printf("It doesn't work\n");
On my system, this prints "It works". I'm using the latest official cJSON release, 1.7.15. I'd recommend using 1.7.15 since it's the latest published version. If you're using the latest code off the master (main) branch, then that could have changes that are not fully vetted yet.
My last test I did using my embedded ESP32 use of cJSON.
I just tried another test by copying the latest source from this repository and compiling it under Linux. I added this test program.
int CJSON_CDECL main(void)
{
const char * jsonString = "{\"current_power\": 218}";
cJSON * json = cJSON_Parse(jsonString);
if (cJSON_HasObjectItem(json, "current_power"))
printf("It works\n");
else
printf("It doesn't work\n");
}
When I compile and run it, it outputs, "It works".