c++ - 从 nlohmann json 访问元素

标签 c++ 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” 中的对象数组>

最佳答案

以下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';
     }
 }

关于c++ - 从 nlohmann json 访问元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38099308/

相关文章:

javascript - AngularJS 和 Bootstrap : ng-repeat causing list to lose formatting

JavaScript 异常 :Uncaught TypeError: Converting circular structure to JSON

c# - JSON.net SelectToken 格式化

c++ - mpg123 链接错误 "_read"和 "_lseek"

c++ - variant_row在数据库模板库(C++)中是如何实现的?

c++ - SDL 瓦片 map 渲染错误 C++/C

c++ - 在 C++ 中迭代包含指针的 vector

c++ - new 失败时是否需要留出一些应急内存?

jquery - 使用 Ajax 和 Json 填充 JQuery Flot 图表

javascript - 有条件地向 JSON 对象添加自定义着色