Skip to content

Instantly share code, notes, and snippets.

@dpruessner
Last active September 4, 2015 02:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpruessner/425c26f7a046359df1f6 to your computer and use it in GitHub Desktop.
Save dpruessner/425c26f7a046359df1f6 to your computer and use it in GitHub Desktop.
Example of JSON parsing using jsmn
/**
* 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