I am using the jsmn JSON parser (source code) to get extract data from a JSON string. jsmn stores the data in tokens that just point to the token boundaries in the JSON string instead of copying the data. For example, jsmn will create tokens like:
Object [0..31]
String [3..7], String [12..16], String [20..23]
Number [27..29]
This method is used to retrieve the actual characters between those values (for String objects):
char* getTextFromJSON(const char *json)
{
json_parser p;
jsontok_t tokens[15];
jsontok_t key;
if (!json) return NULL;
initJsonParser(&p);
parseJson(&p, json, tokens, sizeof(tokens) / sizeof(tokens[0]));
for(unsigned int i = 0; i < sizeof(tokens) / sizeof(tokens[0]); ++i)
{
key = tokens[i];
unsigned int length = key.end - key.start;
char keyString[length + 1];
memcpy(keyString, &json[key.start], length);
keyString[length] = '\0';
if(!strcmp(keyString, "utterance"))
{
key = tokens[i + 1];
length = key.end - key.start;
char* keyString = (char*) malloc(length + 1);
memcpy(keyString, &json[key.start], length);
keyString[length] = '\0';
return keyString;
}
}
return NULL;
}
Here are some JSON examples that would be thrown into the parser:
{"status":0,"id":"432eac38858968c108899cc6c3a4bade-1","hypotheses" [{"utterance":"test","confidence":0.84134156}]}
{"status":5,"id":"695118aaa3d01dc2ac4aa8054d1e5bb0-1","hypotheses":[]}