cjson 注释

cjson支持的注释

  1. 单行注释:// 注释
  2. 多行注释:/* 多行注释 */

解析注释

CJSON_PUBLIC(void) cJSON_Minify(char *json);

CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)

先调用cJSON_Minify函数删除注释,再调用cJSON_Parse函数解析cjson。

json文件

test.json

{

    "idx": 0,  // 单行注释

    /* 多行注释

     * test

    */

    "test": 1.0

}

 test_cjson.cpp

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include "cJSON.h"

int main(int argc, char **argv)
{
    const char *file_name = "test.json";
    int fd = open(file_name, O_RDONLY);
    if (fd == -1) {
        printf("ERROR: Open file %s failed : %s\n", file_name, strerror(errno));
        return -1;
    }

    /* json file size */
    struct stat file_stat;
    int ret = fstat(fd, &file_stat);
    if (ret == -1) {
        printf("ERROR: Get file %s stat failed:%s\n", file_name, strerror(errno));
        close(fd);
        return -1;
    }

    /* malloc memory */
    int json_file_size = file_stat.st_size;
    int json_str_size = file_stat.st_size + 1;
    char *json_str = (char *)malloc(json_str_size);
    if (json_str == NULL) {
        printf("ERROR: malloc failed:%s\n", strerror(errno));
        close(fd);
        return -1;
    }

    /* json file read */
    ret = read(fd, json_str, json_str_size);
    if (ret != json_file_size) {
        printf("ERROR: read return is %d, want to read is %d\n", ret, json_file_size);
        free(json_str);
        close(fd);
        return -1;
    }

    /* json file parse */
    cJSON_Minify(json_str);
    cJSON *cjson_root = cJSON_Parse(json_str);

    cJSON *cjson_idx = cJSON_GetObjectItem(cjson_root, "idx");
    cJSON *cjson_test = cJSON_GetObjectItem(cjson_root, "test");

    printf("idx=%d, test=%f\n", cjson_idx->valueint, cjson_test->valuedouble);

    close(fd);
    free(json_str);
    return 0;
}

编译执行结果

idx=0, test=1.000000

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值