项目地址:GitHub - zserge/jsmn: Jsmn is a world fastest JSON parser/tokenizer. This is the official repo replacing the old one at Bitbucket
主要数据结构:
typedef enum {
JSMN_UNDEFINED = 0,
JSMN_OBJECT = 1 << 0,
JSMN_ARRAY = 1 << 1,
JSMN_STRING = 1 << 2,
JSMN_PRIMITIVE = 1 << 3
} jsmntype_t;
typedef struct jsmntok {
jsmntype_t type;
int start;
int end;
int size;
#ifdef JSMN_PARENT_LINKS
int parent;
#endif
} jsmntok_t;
测试代码:
#include "jsmn.h"
#include
#include
#include
static const char *JSON_STRING =
"{\"user\":\"bob\", \"admin\":false, \"id\":1234, \"profile\":{\"p1\":\"profile1\", \"p2\":[\"profile2\"]}, \"groups\": [\"sales\", \"market\", \"support\", \"r&d\"]}";
int main() {
int i;
int r;
jsmn_parser p;
jsmntok_t t[128]; /* We expect no more than 128 tokens */
jsmn_init(&p);
r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t,
sizeof(t) / sizeof(t[0]));
if (r < 0) {
printf("Failed to parse JSON: %d\n", r);
return 1;
}
char token_str[200];
printf("[type][start][end][size]\n");
for (i = 0; i < r; i++) {
memset(token_str, 0, 200);
memcpy(token_str, JSON_STRING + t[i].start, t[i].end - t[i].start);
printf("token [%d] is: %s\n", i, token_str);
printf("[%4d][%5d][%3d][%4d]\n", t[i].type, t[i].start, t[i].end, t[i].size);
}
return 0;
}
编译运行结果:
[type][start][end][size]
token [0] is: {"user":"bob", "admin":false, "id":1234, "profile":{"p1":"profile1", "p2":["profile2"]}, "groups": ["sales", "market", "support", "r&d"]}
[ 1][ 0][137][ 5]
token [1] is: user
[ 4][ 2][ 6][ 1]
token [2] is: bob
[ 4][ 9][ 12][ 0]
token [3] is: admin
[ 4][ 16][ 21][ 1]
token [4] is: false
[ 8][ 23][ 28][ 0]
token [5] is: id
[ 4][ 31][ 33][ 1]
token [6] is: 1234
[ 8][ 35][ 39][ 0]
token [7] is: profile
[ 4][ 42][ 49][ 1]
token [8] is: {"p1":"profile1", "p2":["profile2"]}
[ 1][ 51][ 87][ 2]
token [9] is: p1
[ 4][ 53][ 55][ 1]
token [10] is: profile1
[ 4][ 58][ 66][ 0]
token [11] is: p2
[ 4][ 70][ 72][ 1]
token [12] is: ["profile2"]
[ 2][ 74][ 86][ 1]
token [13] is: profile2
[ 4][ 76][ 84][ 0]
token [14] is: groups
[ 4][ 90][ 96][ 1]
token [15] is: ["sales", "market", "support", "r&d"]
[ 2][ 99][136][ 4]
token [16] is: sales
[ 4][ 101][106][ 0]
token [17] is: market
[ 4][ 110][116][ 0]
token [18] is: support
[ 4][ 120][127][ 0]
token [19] is: r&d
[ 4][ 131][134][ 0]