Create token "counter" function.

Issue #33 resolved
created an issue

Create a function to count (or estimate) the number of tokens in the given json string.

For example, I wrote this function that seems to work.

unsigned int jsmn_count(const char *js) {
    unsigned int index, count;
    count = 0;
    for (index = 0; js[index] != '\0'; ++index) {
        switch(js[index]) {
            case '{':
            case '[':
            case ',':
            case ':':
    return count;

It usually returns more tokens than is actually needed.

This stays true to the "no dependencies" philosophy. But at the same time it allows the user to avoid guessing how many tokens are in the json.

I only use strict mode, so this function will likely need to be modified for non-strict mode, probably producing a much higher then needed estimate.

Comments (4)

  1. Serge Zaitsev repo owner

    Now token counting is implemented by passing NULL as a tokens parameter to jsmn_parse. But your example is faster and more lightweight, so it would be a nice part of the wiki.

  2. Log in to comment