How to parse a small JSON file with jsmn on an embedded system?

Vincent Zhou picture Vincent Zhou · Jan 17, 2013 · Viewed 17.8k times · Source

I need to parse a small JSON file on an embedded system (only 10K RAM/flash). The JSON is:

{
"data1":[1,2,3,4,5,6,7,8,9],
"data2":[
     [3,4,5,6,1],
     [8,4,5,6,1],
     [10,4,5,3,61],
     [3,4,5,6,1],
     [3,4,5,6,1],
     [3,4,5,6,1] 
]}

jsmn looks great to fit the requirement, but it's not like most JSON parsers, since it only gives you tokens. I tried, but could not figure it out.

Could someone share an example of how to parse it with jsmn?

Answer

Ben Flynn picture Ben Flynn · Feb 5, 2013

jsmn will give you a set of tokens referring to the tokens in your JSON reading left to right.

In your case:

token[0]: (outer) object, 2 children
token[1]: string token ("data1")
token[2]: array, 9 children
token[3]: primitive token (1)
etc...

The basic code to do the parsing is:

int resultCode;
jsmn_parser p;
jsmntok_t tokens[128]; // a number >= total number of tokens

jsmn_init(&p);
resultCode = jsmn_parse(&p, yourJson, tokens, 256);

The other trick is getting the value of a token. The token contains the start and end points of the data on your original string.

jsmntok_t key = tokens[1];
unsigned int length = key.end - key.start;
char keyString[length + 1];    
memcpy(keyString, &yourJson[key.start], length);
keyString[length] = '\0';
printf("Key: %s\n", keyString);

With that you should be able to figure you how to iterate through your data.