C 语言解析 json 格式数据

本文深入探讨了使用json_scanf函数解析复杂JSON字符串的方法,包括处理数组、字符串、布尔值及自定义扫描函数等高级功能,适用于后端开发中对JSON数据的精细控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:https://github.com/cesanta/frozen

 

函数:

函数原型:
int json_scanf(const char *str, int str_len, const char *fmt, ...);

示例1:
//str is a JSON string :{ "a": 123, "b": "hi", c: true }

int value = 0;
json_scanf(str, strlen(str), "{c: %B}", &value);


示例2:

//str has the following JSON string (notice keys are out of order):
//{ "a": 123, "d": true, "b": [1, 2], "c": "hi" }


int a = 0, d = 0;
  char *c = NULL;
  void *my_data = NULL;
  json_scanf(str, strlen(str), "{ a:%d, b:%M, c:%Q, d:%B }",
             &a, scan_array, my_data, &c, &d);

  // This function is called by json_scanf() call above.
  // str is "[1, 2]", user_data is my_data.
  static void scan_array(const char *str, int len, void *user_data) {
    struct json_token t;
    int i;
    printf("Parsing array: %.*s\n", len, str);
    for (i = 0; json_scanf_array_elem(str, len, "", i, &t) > 0; i++) {
      printf("Index %d, token [%.*s]\n", i, t.len, t.ptr);
    }
  }


Several extra format specifiers are supported:

  • %B: consumes int * (or char *, if sizeof(bool) == sizeof(char)), expects boolean true or false.
  • %Q: consumes char **, expects quoted, JSON-encoded string. Scanned string is malloc-ed, caller must free() the string.
  • %V: consumes char **int *. Expects base64-encoded string. Result string is base64-decoded, malloced and NUL-terminated. The length of result string is stored in int * placeholder. Caller must free() the result.
  • %H: consumes int *char **. Expects a hex-encoded string, e.g. "fa014f". Result string is hex-decoded, malloced and NUL-terminated. The length of the result string is stored in int * placeholder. Caller must free() the result.
  • %M: consumes custom scanning function pointer and void *user_data parameter - see json_scanner_t definition.
  • %T: consumes struct json_token *, fills it out with matched token.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值