C 语言 json 库的基本用法

首先去下载json-c lib

下载地址:git clone http://25thandClement.com/~william/projects/libjson.git


下载完成后,src是json库文件, exampel中是两个实例文件。

但是讲解的不是很清楚。

如果我们要生成json格式并打印出出来,我们就可以使用如下代码:


#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include "json.h"

int main (void)
{
    int error;
    struct json *J;

    J = json_open(JSON_F_NONE, &error);
    setlocale(LC_ALL, "");
    json_push(J, ".Peoples");

    //json_push(J, "thumbs[]");
    json_setstring(J, "Andow", ".MEN[0].name");
    json_setstring(J, "555 123 456", "MEN[0].phone");

    json_setstring(J, "Andow1", ".MEN[1].name");
    json_setstring(J, "555 123 456", "MEN[1].phone");

    json_pop(J);
    json_pop(J);

    json_push(J, ".Peoples.thumb");
    json_setstring(J, "Andow", "name");
    json_setstring(J, "12344566", "phone");
    json_setnumber(J, 123, "weigh");
    json_pop(J);
    json_setstring(J, "Beijing", ".Peoples.$", "Local");

    //json_pop(J)

    json_setstring(J, "Andow", ".thumbs[0]");
    json_setstring(J, "androw1", ".thumbs[#]", json_count(J, ".thumbs"));
    json_push(J, ".thumbs[#]", json_count(J, ".thumbs"));
    json_setstring(J, "apple", ".");
    json_pop(J);
    json_setstring(J, "intel", ".thumbs[3]");


    json_printfile(J, stdout, JSON_F_PRETTY);

    return EXIT_SUCCESS;
}

运行结果如下:

{
        "Peoples" : {
                "Local" : "Beijing",
                "MEN" : [
                        {
                                "name" : "Andow",
                                "phone" : "555 123 456"
                        },
                        {
                                "name" : "Andow1",
                                "phone" : "555 123 456"
                        }
                ],
                "thumb" : {
                        "name" : "Andow",
                        "phone" : "12344566",
                        "weigh" : 123
                }
        },
        "thumbs" : [
                "Andow",
                "androw1",
                "apple",
                "intel"
        ]
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值