当前位置: 首页 > 工具软件 > libjson > 使用案例 >

用libjson-glib处理json数据

傅越
2023-12-01

json是一个轻量级的数据交换格式,在我们的一些大型程序时,可以用它来存储一些数据信息。前一篇演示了nodejs解析json的过程,今天我们要用我们传统的c语言来处理。

要用c语言来处理我们就需要依赖一些额外的库,虽然处理json的c库很多,但是今天我们就选择libjson-glib.

第一,在ubuntu14.04 安装libjson-glib

$ sudo apt-get install libjson-glib-1.0-0 libjson-glib-dev

第二,准备json测试文件, test.json:

{
“person”: {
“name”: “wanger”,
“birth”: “1999”
}
}

第三,创建main.c 来处理json文件

/*gcc -o testjson main.c pkg-config --cflags --libs json-glib-1.0
*/

#include <json-glib/json-glib.h>

static void print_cb(JsonObject *obj, const gchar *key, JsonNode *val, gpointer user_data)
{
gchar *rel_val = “”;
GType type = json_node_get_value_type(val);
g_message(“typename:%s”, g_type_name(type));

    if (g_type_is_a(type, G_TYPE_STRING)) {
            rel_val =(gchar *)json_node_get_string(val);
    }

    g_message("%s:%s", key, rel_val);

}

int main(int argc, char *argv[])
{
if (argc < 2) {
g_error(“Usage:\n\t%s <json_path>”, argv[0]);
return 1;
}

    JsonParser *parser = json_parser_new();
    GError *error = NULL;
    json_parser_load_from_file(parser, argv[1], &error);
    if (error) {
            g_error("Unable to parse %s: %s", argv[1], error->message);
            g_error_free(error);
            g_object_unref(parser);
            return 1;
    }

    JsonNode *root = json_parser_get_root(parser);
    JsonObject *root_obj = json_node_get_object(root);
    if (json_object_has_member(root_obj, "person")) {
            JsonObject *person = json_object_get_object_member(root_obj, "pe   rson");
            json_object_foreach_member(person, print_cb, NULL);
    }
    g_object_unref(parser);
    return 0;

}
第四,编译并运行

$ gcc -o testjson main.c pkg-config --cflags --libs json-glib-1.0

$ testjson test.json
** Message: typename:gchararray
** Message: name:wanger
** Message: typename:gchararray
** Message: birth:1999
————————————————
版权声明:本文为CSDN博主「tlight」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/tlight/article/details/48244021

 类似资料: