使用c++读取json文件的代码
时间: 2024-05-02 21:18:21 浏览: 107
C/C++将json文件读取到内存的接口使用demo
以下是使用c语言读取json文件的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"
int main() {
char *filename = "data.json";
char *data = NULL;
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open %s\n", filename);
return 1;
}
fseek(fp, 0, SEEK_END);
long length = ftell(fp);
fseek(fp, 0, SEEK_SET);
data = (char *) malloc(length + 1);
fread(data, 1, length, fp);
fclose(fp);
data[length] = '\0';
cJSON *json = cJSON_Parse(data);
if (json == NULL) {
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
printf("Error before: %s\n", error_ptr);
}
return 1;
}
cJSON *name = cJSON_GetObjectItemCaseSensitive(json, "name");
if (cJSON_IsString(name) && (name->valuestring != NULL)) {
printf("Name: %s\n", name->valuestring);
}
cJSON *age = cJSON_GetObjectItemCaseSensitive(json, "age");
if (cJSON_IsNumber(age)) {
printf("Age: %d\n", age->valueint);
}
cJSON *address = cJSON_GetObjectItemCaseSensitive(json, "address");
cJSON *city = cJSON_GetObjectItemCaseSensitive(address, "city");
if (cJSON_IsString(city) && (city->valuestring != NULL)) {
printf("City: %s\n", city->valuestring);
}
cJSON_Delete(json);
free(data);
return 0;
}
```
此代码使用了cJSON库,需要先安装该库。在Ubuntu下,可以使用以下命令安装:
```
sudo apt-get install libjansson-dev
```
阅读全文