从 nlohmann json 访问元素

新手上路,请多包涵

我的 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" 对象数组

原文由 Jeremy Kuah 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 528
1 个回答

以下 链接 说明了访问 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';
     }
 }

原文由 Jeremy Kuah 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题