如何使用nlohmann :: json将json对象转换为地图? [英] How to convert a json object to a map with nlohmann::json?

查看:1502
本文介绍了如何使用nlohmann :: json将json对象转换为地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,使用nlohmann :: json,我可以做到

For example, with nlohmann::json, I can do

map<string, vector<int>> m = { {"a", {1, 2}}, {"b", {2, 3}} };
json j = m;

但是我不能做

m = j;

是否可以使用nlohmann :: json将json对象转换为地图?

Any way to convert a json object to a map with nlohmann::json?

推荐答案

nlomann :: json可以使用get<typename BasicJsonType>() const

nlomann::json can convert Json objects to to most standard STL containers with get<typename BasicJsonType>() const

示例:

// Raw string to json type
auto j = R"(
{
  "foo" :
  {
    "bar" : 1,
    "baz" : 2
  }
}
)"_json;

// find object and convert to map
std::map<std::string, int> m = j.at("foo").get<std::map<std::string, int>>();
std::cout << m.at("baz") << "\n";
// 2

这篇关于如何使用nlohmann :: json将json对象转换为地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆