我的 JSON 是这样的:
{
"apps":[
{
"id":"x",
"val":"y",
}
]
}
我可以id
通过循环获得值“x”,并在何时it.first
退出id
:
for (const ptree::value_type &app : root.get_child("apps"))
{
for (const ptree::value_type &it : app.second) {
if (it.first == "id") {
std::cout << it.second.get_value<std::string>().c_str() << std::endl;
}
}
}
但是,我想要的是通过以下方式获得id
' 值:
std::cout << root.get<std::string>("apps[0].id").c_str() << std::endl;
当然这对我没有任何意义,因为我可能使用了错误的语法来访问应用程序数组的第一个元素。这可能必须以不同的方式一起完成。
我只发现了这种丑陋而危险的方法:
std::cout << root.get_child("apps").begin()->second.begin()->second.get_value<std::string>().c_str() << std::endl;
我不能真正以这种方式使用它,因为当数组为空时它不会抛出异常,它将核心转储!
以下是整个程序,以使任何想要帮助的人更容易:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree;
int main()
{
std::stringstream ss("{\"apps\":[{\"id\":\"x\",\"val\":\"y\"}]}");
ptree root;
read_json(ss, root);
for (const ptree::value_type &app : root.get_child("apps"))
{
for (const ptree::value_type &it : app.second) {
if (it.first == "id") {
std::cout << it.second.get_value<std::string>().c_str() << std::endl;
}
}
}
std::cout << root.get_child("apps").begin()->second.begin()->second.get_value<std::string>().c_str() << std::endl;
return 0;
}