c++ json转map
时间: 2023-07-05 12:31:54 浏览: 251
你可以使用第三方库如`nlohmann/json`来实现C++中JSON转Map的功能。下面是一个简单的示例代码:
```c++
#include <iostream>
#include <map>
#include "json.hpp"
using json = nlohmann::json;
int main() {
std::string jsonStr = R"(
{
"key1": "value1",
"key2": {
"innerKey1": 123,
"innerKey2": "value2"
}
}
)";
json jsonObj = json::parse(jsonStr);
std::map<std::string, json> myMap = jsonObj;
for (auto const& [key, val] : myMap) {
std::cout << key << ": " << val.dump() << std::endl;
}
return 0;
}
```
这里我们使用`json::parse`将JSON字符串转换为JSON对象,然后将其赋值给一个`std::map<std::string, json>`类型的变量,从而实现了JSON转Map的功能。注意到`nlohmann/json`库的`json`类型支持隐式转换,所以可以直接将其赋值给`std::map`类型的变量。最后使用`dump`函数将`json`类型的值转换为字符串输出。
阅读全文
相关推荐
















