Page 1 of 1

Method to catch ill-formed json string with cJSON_Parse

Posted: Fri Oct 27, 2017 5:46 pm
by rwel59
Had a badly formed json string that I tried to parse and threw exception causing reset. Is there a method to catch this kind of stuff?

Attempted to try-catch but couldn't get that to work.

Re: Method to catch ill-formed json string with cJSON_Parse

Posted: Fri Oct 27, 2017 10:18 pm
by tele_player
Do you know what is ill-formed in your JSON string?

Re: Method to catch ill-formed json string with cJSON_Parse

Posted: Fri Oct 27, 2017 11:13 pm
by rwel59
I was missing a bracket { - Easily fixed.

I was trying to figure out a generic method so that I can confirm I have a valid json before trying to parse, or catching an error when I do parse.

Re: Method to catch ill-formed json string with cJSON_Parse

Posted: Sat Oct 28, 2017 2:54 am
by tele_player
cJSON_Parse should return 0 on a failed parse. Did you check it’s return value?

Re: Method to catch ill-formed json string with cJSON_Parse

Posted: Sat Oct 28, 2017 4:40 pm
by rwel59
Though I tried that. Here is what I did...
std::string json_str = "{\"name\":\"Johnny\", \"age\":30, \"city\":\"New York\"}";
ESP_LOGD(TAG, "json parse : %d\n", (int)cJSON_Parse(text.c_str()));
return JsonObject(cJSON_Parse(text.c_str()));
when I executed this, json parse : 1073525068

modified the string to: std::string json_str = "\"name\":\"Johnny\", \"age\":30, \"city\":\"New York\"}";
(removed the initial {)
when I executed this, json parse : 1073525068

Re: Method to catch ill-formed json string with cJSON_Parse

Posted: Sat Oct 28, 2017 6:44 pm
by tele_player
In both those cases, cJSON_Parse didn’t crash (they successfully returned), so what did?

Re: Method to catch ill-formed json string with cJSON_Parse

Posted: Sun Oct 29, 2017 1:04 pm
by rwel59
You are correct. The exception is occurring when I attempt to perform an action after the parse. The error happens when node->valuestring is called because node=nullptr. So, I can catch the error here. Thanks for the help...

cJSON *node = cJSON_GetObjectItem(m_node, name.c_str());
ESP_LOGD(TAG, "json getString\n");
if(node == nullptr) ESP_LOGD(TAG, "json getString null pointer\n");
return std::string(node->valuestring);