zserge / jsmn

Jsmn is a world fastest JSON parser/tokenizer. This is the official repo replacing the old one at Bitbucket
MIT License
3.68k stars 783 forks source link

First child, next sibling #68

Open azim0ff opened 8 years ago

azim0ff commented 8 years ago

Hey, just wanted to share a small tweak to JSMN that I've been using to help with traversing the token tree. Following how things are done in JSMN_PARENT_LINKS, I've added JSMN_FIRST_CHILD_NEXT_SIBLING.

I use it to help with parsing jsonrpc requests. For example, if I have a json string like this:

{"jsonrpc":"2.0","method":"echo","params":["hello", "world"],"id":1}

... and want to get the value of "id", I iterate over the "first level" elements.

jsmntok_t tokens[TOKENS_MAXSIZE];
jsmntok_t* value;

int self = tokens[0].first_child;
if (self == -1) {
    //error
}

do {
    if (strncmp("id", json_string + tokens[self].start, 
                        tokens[self].end - tokens[self].start) == 0)
    {
        value = (tokens[self].first_child == -1) 
                        ? NULL : &tokens[tokens[self].first_child];
    }
} while ( (self = tokens[self].next_sibling) != -1);

Would you be interested in this feature?

frobnitzem commented 7 years ago

My implementation of skip-lists does something like this. Parsing your string, {"jsonrpc":"2.0","method":"echo","params":["hello", "world"],"id":1} creates 10 tokens: '{'(10) "jsonrpc"(2) "2.0"(1) "method"(2) "echo"(1) "params"(4) '['(3) "hello"(1) "world"(1) "id"(2) 1(1)

Skip instead of count means you can always jump directly the next sibling.