C语言 json parser - JSMN

项目地址: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 <stdio.h>
#include <stdlib.h>
#include <string.h>

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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值