In my application I need to receive and parse small json strings. That works fine as long as the json doesn't contain any booleans or negative numbers.
Here is some test code to illustrate my problem (I'm using the non-os sdk version 2.0.0):
Code: Select all
/* this values are returned by jsonparse_next() but aren't defined in json.h for some reason
* so I gave them my own names here
*/
#define JSON_TYPE_OBJECT_END '}'
#define JSON_TYPE_ARRAY_END ']'
#define JSON_TYPE_DELIMITER ','
void ICACHE_FLASH_ATTR
json_parse(char *json_data, uint8_t json_len)
{
struct jsonparse_state parse_state;
int json_type;
char buf[64];
jsonparse_setup(&parse_state, json_data, json_len);
while (json_type = jsonparse_next(&parse_state)) {
switch (json_type) {
case JSON_TYPE_OBJECT:
os_printf("{ ");
break;
case JSON_TYPE_OBJECT_END:
os_printf(" }");
break;
case JSON_TYPE_ARRAY:
os_printf("[");
break;
case JSON_TYPE_ARRAY_END:
os_printf("]");
break;
case JSON_TYPE_DELIMITER:
os_printf(", ");
case JSON_TYPE_CALLBACK:
break;
case JSON_TYPE_PAIR_NAME:
jsonparse_copy_value(&parse_state, buf, 64);
os_printf("%s", buf);
break;
case JSON_TYPE_PAIR:
os_printf(": ");
break;
case JSON_TYPE_NUMBER:
os_printf("%d", jsonparse_get_value_as_int(&parse_state));
break;
case JSON_TYPE_INT:
os_printf("%d", jsonparse_get_value_as_int(&parse_state));
break;
case JSON_TYPE_STRING:
jsonparse_copy_value(&parse_state, buf, 64);
os_printf("\"%s\"", buf);
break;
case JSON_TYPE_TRUE:
os_printf("true");
break;
case JSON_TYPE_FALSE:
os_printf("false");
break;
default:
os_printf(" unhandled type %d ", json_type);
}
}
if (json_type == JSON_TYPE_ERROR && parse_state.error != JSON_ERROR_OK) {
os_printf(" json parse error");
}
os_printf("\n");
}
void ICACHE_FLASH_ATTR
json_test()
{
char json_pair_number[] = "{ \"number\": 23 }";
char json_pair_array[] = "{ \"array\": [5,24] }";
char json_pair_string[] = "{ \"string\": \"hello json\" }";
char json_pair_negative_number[] = "{ \"number\": -3 }";
char json_pair_boolean[] = "{ \"success\": true }";
json_parse(json_pair_number, os_strlen(json_pair_number));
json_parse(json_pair_array, os_strlen(json_pair_array));
json_parse(json_pair_string, os_strlen(json_pair_string));
json_parse(json_pair_negative_number, os_strlen(json_pair_negative_number));
json_parse(json_pair_boolean, os_strlen(json_pair_boolean));
}
Calling json_test() results in the following output:
{ number: 23 }
{ array: [5, 24] }
{ string: "hello json" }
{ number:
{ success:
As you can see the first three example strings are parsed successful. If, however, the json contains a negative number or boolean the parser just seems to stop without an error.
Does anyone spot an error in my approach? Does anyone parsed json containing those types successful?
Any help is appreciated.
Thanks very much!