cjson支持的注释
- 单行注释:// 注释
- 多行注释:/* 多行注释 */
解析注释
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