Last active
September 4, 2015 02:08
-
-
Save dpruessner/425c26f7a046359df1f6 to your computer and use it in GitHub Desktop.
Example of JSON parsing using jsmn
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Extract the string value of a JSON key out of a parsed JSON structure. | |
* | |
* @param json Generic JSON stateful structure as returned/modified by JSMN library | |
* @param name Null-terminated string with key name to lookup | |
* @param json_val This string pointer will be updated with the location of the data in the JSON buffer. | |
* | |
* @return -1 if no key found, otherwise we return the length of the string | |
* (excluding NULL-terminator; just like strlen() would return). | |
* | |
*/ | |
int json_get_key_value(json_stateful_t *json, char *name, int length, char** json_val) | |
// Do stuff (probably loop through `json` member elements) | |
if ( strncmp(name, &json[key.start], length) == 0) { | |
jsmntok_t value_key = tokens[i + 1]; | |
unsigned int value_length = value_key.end - value_key.start; | |
*json_val = json + value_key.start; | |
sprintf(print_buf, "test result %i ",value_key.start); | |
HalUARTWrite(HAL_UART_PORT_0,(uint8 *)print_buf, strlen(print_buf)); | |
return value_length; | |
} | |
// Check everything else. Nothing matches | |
return -1; | |
} | |
// Use the stuff | |
#define JSON_BUFFER_LEN 512 // Half-kB buffer | |
char json_buffer[JSON_BUFFER_LEN]; | |
int main(void) { | |
// Read JSON data (simplified to a blocking function) | |
uart_read_json(json_buffer); | |
// Parse JSON | |
json_stateful_t json; | |
json_parse_string(&json, json_buffer); | |
// Get a key-value | |
char *wifi_ssid; | |
int wifi_ssid_len; | |
if ((wifi_ssid_len = json_get_key_value(&json, "wifi_ssid", strlen("wifi_ssid"), &wifi_ssid)) < 0 ) { | |
// Error | |
} | |
// Make use of wifi_name. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment