Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First child, next sibling #68

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

azim0ff
Copy link

@azim0ff azim0ff commented Jan 23, 2016

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
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants