nlohmann_json读取一个json文件中的数组
时间: 2023-06-21 20:23:42 浏览: 127
要读取一个 JSON 文件中的数组,我们可以使用 `nlohmann_json` 库提供的 `json::parse()` 函数来解析 JSON 文件,然后再遍历数组。以下是一个示例代码:
```c++
#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
// 打开 JSON 文件
std::ifstream ifs("example.json");
// 读取 JSON 文件
json j = json::parse(ifs);
// 遍历 JSON 数组
for (auto& elem : j["data"]) {
std::cout << elem << std::endl;
}
return 0;
}
```
在这个示例中,我们首先打开了一个名为 `example.json` 的 JSON 文件,然后使用 `json::parse()` 函数将其解析成一个 `json` 对象。由于这个 JSON 对象中含有一个名为 `data` 的数组,我们可以使用 `j["data"]` 来访问它,并使用范围 for 循环来遍历其中的元素,并将每个元素输出到控制台上。
需要注意的是,在读取 JSON 文件时,我们首先必须打开它,然后使用 `json::parse()` 函数将其解析成一个 `json` 对象。如果 JSON 文件无法打开或解析失败,程序将抛出异常。