转自: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 *
(orchar *
, ifsizeof(bool) == sizeof(char)
), expects booleantrue
orfalse
. - %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 inint *
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 inint *
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.