gpt4 book ai didi

c++ - 从 nlohmann json 访问元素

转载 作者:太空狗 更新时间:2023-10-29 20:10:40 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com