Method to catch ill-formed json string with cJSON_Parse

rwel59
Posts: 97
Joined: Thu Oct 12, 2017 3:32 pm

Method to catch ill-formed json string with cJSON_Parse

Postby rwel59 » Fri Oct 27, 2017 5:46 pm

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.

tele_player
Posts: 90
Joined: Sun Jul 02, 2017 3:38 am

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

Postby tele_player » Fri Oct 27, 2017 10:18 pm

Do you know what is ill-formed in your JSON string?

rwel59
Posts: 97
Joined: Thu Oct 12, 2017 3:32 pm

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

Postby rwel59 » Fri Oct 27, 2017 11:13 pm

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.

tele_player
Posts: 90
Joined: Sun Jul 02, 2017 3:38 am

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

Postby tele_player » Sat Oct 28, 2017 2:54 am

cJSON_Parse should return 0 on a failed parse. Did you check it’s return value?

rwel59
Posts: 97
Joined: Thu Oct 12, 2017 3:32 pm

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

Postby rwel59 » Sat Oct 28, 2017 4:40 pm

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

tele_player
Posts: 90
Joined: Sun Jul 02, 2017 3:38 am

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

Postby tele_player » Sat Oct 28, 2017 6:44 pm

In both those cases, cJSON_Parse didn’t crash (they successfully returned), so what did?

rwel59
Posts: 97
Joined: Thu Oct 12, 2017 3:32 pm

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

Postby rwel59 » Sun Oct 29, 2017 1:04 pm

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

Who is online

Users browsing this forum: No registered users and 95 guests