c++读取JSON文件
时间: 2023-11-05 21:50:58 浏览: 72
在 C++ 中读取 JSON 文件,可以使用第三方库来实现。常用的 JSON 库有:
- JSON for Modern C++:https://github.com/nlohmann/json
- RapidJSON:https://github.com/Tencent/rapidjson
这里以 JSON for Modern C++ 为例进行说明。
首先需要在代码中包含 JSON for Modern C++ 的头文件:
```cpp
#include <nlohmann/json.hpp>
```
然后可以使用该库提供的函数来读取 JSON 文件。假设我们有一个名为 "data.json" 的 JSON 文件,其内容如下:
```json
{
"name": "John",
"age": 30,
"isMale": true,
"hobbies": ["reading", "swimming", "traveling"],
"address": {
"city": "New York",
"state": "NY",
"zip": "10001"
}
}
```
我们可以使用如下代码来读取该文件:
```cpp
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
std::ifstream file("data.json");
if (!file.is_open()) {
std::cerr << "Failed to open file\n";
return 1;
}
json j;
file >> j;
std::cout << "Name: " << j["name"] << '\n';
std::cout << "Age: " << j["age"] << '\n';
std::cout << "Is male: " << j["isMale"] << '\n';
std::cout << "Hobbies:\n";
for (const auto& h : j["hobbies"]) {
std::cout << "- " << h << '\n';
}
std::cout << "Address:\n";
std::cout << "City: " << j["address"]["city"] << '\n';
std::cout << "State: " << j["address"]["state"] << '\n';
std::cout << "ZIP code: " << j["address"]["zip"] << '\n';
return 0;
}
```
输出结果如下:
```
Name: John
Age: 30
Is male: true
Hobbies:
- reading
- swimming
- traveling
Address:
City: New York
State: NY
ZIP code: 10001
```
这里使用 ifstream 来打开文件,然后使用 nlohmann::json 类型的变量 j 来保存读取到的 JSON 数据。读取完成后,可以通过 j 的成员访问运算符来访问 JSON 中的数据。例如,j["name"] 表示 JSON 对象中名为 "name" 的字段的值。如果该字段不存在,将返回一个 null 值。对于数组和对象类型的字段,则可以使用迭代器来遍历其中的元素。
需要注意的是,JSON for Modern C++ 支持多种类型的 JSON 值,包括字符串、数字、布尔值、数组、对象、null 等。在使用时需要根据实际情况进行类型转换。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)