#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
// 读取 JSON 文件
std::ifstream file("example.json");
if (!file.is_open()) {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
// 解析 JSON 文件内容到 json 对象
json j;
file >> j;
file.close();
// 将 JSON 对象转换为 C++ map
std::map<std::string, int> my_map = j.get<std::map<std::string, int>>();
// 打印 map 内容
for (const auto& [key, value] : my_map) {
std::cout << key << ": " << value << std::endl;
}
return 0;
}
#include <nlohmann/json.hpp>
引入了 nlohmann/json
库,用于处理 JSON 数据。using json = nlohmann::json;
为 nlohmann::json
类型定义了一个简短的别名 json
。std::ifstream
打开并读取 JSON 文件。json
对象。get<std::map<std::string, int>>()
方法将 JSON 对象转换为 C++ 的 std::map
。std::map
并打印键值对。确保你已经安装了 nlohmann/json
库。可以使用以下命令通过包管理器安装:
pip install nlohmann_json
或者在 CMake 中添加依赖项。
下一篇:js 数组 reduce
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站