C++读取文件中josn数据,一个Key对应多个value
时间: 2025-01-12 11:00:24 浏览: 59
在C++中读取JSON数据,特别是当一个键关联着多个值(也称为数组或列表)时,可以使用第三方库如RapidJSON、nlohmann/json或者其他支持JSON解析的库。这里我们假设你使用了nlohmann/json库。
首先,你需要安装并包含必要的库头文件,然后创建一个函数来读取文件:
```cpp
#include <fstream>
#include "json.hpp" // 使用nlohmann/json库
using json = nlohmann::json;
std::vector<std::string> read_json_values(const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
throw std::runtime_error("Failed to open the file.");
}
json j;
file >> j; // 尝试从文件中读取JSON
std::vector<std::string> values;
for (const auto& item : j["key_name"]) { // 假设你想获取名为"key_name"的对象的值
if (item.is_string()) {
values.push_back(item.get<std::string>());
}
}
return values;
}
// 示例用途
int main() {
try {
const std::string file_path = "example.json";
std::vector<std::string> values = read_json_values(file_path);
for (const auto& value : values) {
std::cout << value << "\n";
}
} catch (const std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
```
在这个例子中,`read_json_values`函数打开文件,解析JSON内容,并将"key_name"对应的字符串值存储在一个`std::vector<std::string>`中。注意,实际的键名应替换为你的JSON文件中实际对应的键名。
阅读全文
相关推荐


















