alisdair / jsmn-example

Sample code for using Serge Zaitsev's awesome jsmn JSON parsing library
http://alisdair.mcdiarmid.org/2012/08/14/jsmn-example.html
Other
100 stars 30 forks source link

jsmntok_t.size is 0 #2

Closed ker2x closed 10 years ago

ker2x commented 10 years ago

Friendly greetings ! I'm running this code :

static char* tk_to_str(const char* json, jsmntok_t t) {
        char* str = malloc(t.end - t.start + 1);
        if(str == NULL) {
                fprintf(stderr, "tk_to_str : malloc failed\n");
                return NULL;
        }
        str = memcpy(str, json + t.start , t.end - t.start + 1);
        printf("size : %d\n", t.end - t.start);
        str[t.end - t.start] = '\0';
        return str;
}

i have to use "t.end - t.start" because t.size is always 0. am i doing something wrong ? am i mistaken about size ? is it a bug ? thank you

alisdair commented 10 years ago

This repository is not for jsmn itself. This is just my example code for jsmn, which you do not appear to be using. Please direct jsmn questions to the author: http://zserge.com/jsmn.html

To answer your question: t.size is the number of child tokens, not the byte length of the token in the input stream. From the docs:

typedef struct {
    jsmntype_t type; /* Token type */
    int start;       /* Token start position */
    int end;         /* Token end position */
    int size;        /* Number of child (nested) tokens */
} jsmntok_t;

So you are not incorrect about using t.end - t.start.

ker2x commented 10 years ago

Oooops wrong repo, sorry about that and thank you for your instant reply ! Have a nice day \o/