您也可以查看cisson。以下来自他们的 README 的示例非常简单,可以实现您正在寻找的内容:
让我们把下面的C对象转成JSON
struct foo = {
.foo = "bar",
.array = {1, 2, 3},
.question = true
};
#define CISSON_IMPLEMENTATION
#include "cisson.h"
int main(void) {
struct tree tree = {0};
START_AND_PUSH_TOKEN(&tree, ROOT, "#custom root");
/* every token we push will be bound to the current root */
START_AND_PUSH_TOKEN(&tree, OBJECT, "{");
PUSH_ROOT(&tree);
/* "PUSH_ROOT" will change the current root to the previously
* pushed token so every following
* token will be bound to the object token */
START_AND_PUSH_TOKEN(&tree, STRING, "\"foo\"");
PUSH_ROOT(&tree);
/* next token will be bound to the key */
START_AND_PUSH_TOKEN(&tree, STRING, "\"bar\"");
CLOSE_ROOT(&tree);
/* now the root is no more the key but the object */
START_AND_PUSH_TOKEN(&tree, STRING, "\"array\"");
PUSH_ROOT(&tree);
START_AND_PUSH_TOKEN(&tree, ARRAY, "[");
PUSH_ROOT(&tree);
START_AND_PUSH_TOKEN(&tree, NUMBER, "1");
START_AND_PUSH_TOKEN(&tree, NUMBER, "2");
START_AND_PUSH_TOKEN(&tree, NUMBER, "3");
CLOSE_ROOT(&tree); /* the array */
CLOSE_ROOT(&tree); /* the object property */
START_AND_PUSH_TOKEN(&tree, STRING, "\"question\"");
PUSH_ROOT(&tree);
START_AND_PUSH_TOKEN(&tree, TRUE, "true");
puts(to_string(&tree)); /* {"foo":"bar","array":[1,2,4],"question":true} */
}