我的 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/