【问题标题】:accessing elements from nlohmann json从 nlohmann json 访问元素
【发布时间】:2016-11-01 03:27:59
【问题描述】:

我的 JSON 文件与此类似

{
  "active" : false,
  "list1" : ["A", "B", "C"],
  "objList" : [
    {
     "key1" : "value1",
     "key2" : [ 0, 1 ]
    }
   ]
}

现在使用 nlohmann json,我已经设法存储它,当我转储 jsonRootNode.dump() 时,内容被正确表示。

但是我找不到访问内容的方法。

我尝试了jsonRootNode["active"]jsonRootNode.get() 和使用json::iterator,但仍然不知道如何检索我的内容。

我正在尝试检索"active",来自"list1" 的数组和来自"objList" 的对象数组

【问题讨论】:

  • 下面的答案没有解决每种方法之间的差异。 get() 返回copy of valueat() 返回refoperator[] 返回const ref

标签: c++ json


【解决方案1】:

下面的link 解释了访问 JSON 中元素的方法。如果链接超出范围,这里是代码

#include <json.hpp>

 using namespace nlohmann;

 int main()
 {
     // create JSON object
     json object =
     {
         {"the good", "il buono"},
         {"the bad", "il cativo"},
         {"the ugly", "il brutto"}
     };

     // output element with key "the ugly"
     std::cout << object.at("the ugly") << '\n';

     // change element with key "the bad"
     object.at("the bad") = "il cattivo";

     // output changed array
     std::cout << object << '\n';

     // try to write at a nonexisting key
     try
     {
         object.at("the fast") = "il rapido";
     }
     catch (std::out_of_range& e)
     {
         std::cout << "out of range: " << e.what() << '\n';
     }
 }

【讨论】:

  • 感谢您的帮助!例如,您可以通过用于访问 key2 的代码吗?您也可以将此主题标记为已解决。
  • 有没有办法将它们转换为字符串? :(
  • @BenjaminGoutfer 没问题 :)
  • @kayleeFrye_onDeck 我已经有一段时间没有发布这个了:\ 但我很确定有一个简单的转换
  • @JeremyKuah,由于知道键名及其值类型,我最终使用了get。否则这会很烦人......为了动态处理它,我通过迭代元素来解决它,但这是一个草率的黑客攻击。
【解决方案2】:

如果其他人仍在寻找答案。您可以使用与写入nlohmann::json 对象相同的方法访问内容。例如从 问题中的json:

{
  "active" : false,
  "list1" : ["A", "B", "C"],
  "objList" : [
    {
      "key1" : "value1",
      "key2" : [ 0, 1 ]
    }
  ]
}

只是做:

nlohmann::json jsonData = nlohmann::json::parse(your_json);
std::cout << jsonData["active"] << std::endl;    // returns boolean
std::cout << jsonData["list1"] << std::endl;     // returns array

如果"objList" 只是一个对象,您可以通过以下方式检索其值:

std::cout << jsonData["objList"]["key1"] << std::endl;    // returns string
std::cout << jsonData["objList"]["key2"] << std::endl;    // returns array

但由于 "objList" 是键/值对列表,因此要访问其值,请使用:

for(auto &array : jsonData["objList"]) {
    std::cout << array["key1"] << std::endl;    // returns string
    std::cout << array["key2"] << std::endl;    // returns array
}

考虑到"objList" 是大小为 1 的数组,循环只运行一次。

希望对某人有所帮助

【讨论】:

    【解决方案3】:

    我真的很喜欢在 C++ 中使用它:

    for (auto& el : object["list1"].items())
    {
      std::cout << el.value() << '\n';
    }
    

    它将遍历数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 2012-09-09
      • 1970-01-01
      相关资源
      最近更新 更多