事实:
- 我正在使用 VS2013 并使用 C++ 进行开发。
- 我正在使用 boost API 从标准/合法的 json 文件中获取值。
- 我无法提取 name4.js、name5.js 和 name6.js 名称。
- 我已在整个 stackoverflow/Google 上进行了搜索,但没有找到对我正在使用的以下 json 文件的任何解释。
json文件:
{
"background": {
"scripts": [ "name1.js", "name2.js", "name3.js" ]
},
"default_popup": "popup.html",
"default_title": "__MSG_name__",
"content_scripts": [ {
"all_frames": true,
"js": [ "name4.js", "name5.js", "name6.js" ],
"match_about_blank": true,
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_start"
}, {
"all_frames": true,
"js": [ "include.postload.js" ],
"match_about_blank": true,
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_end"
} ]
}
什么有效:
正如您在下面的代码中看到的,我能够使用“background.scripts”(boost 网站上的示例)提取“name1.js”、“name2.js”和“name3.js” :
boost::property_tree::ptree doc; boost::property_tree::read_json("C:/Temp\\manifest.json", doc); std::vector<string> jsFiles; try{ BOOST_FOREACH(boost::property_tree::ptree::value_type& framePair, doc.get_child("background.scripts")){ jsFiles.push_back(framePair.second.data()); } } catch (boost::exception const &ex){}
什么不起作用:
- 我想提取其余的 js 名称,它们是:
- name4.js
- name5.js
- name6.js
我无法使用以下代码让它工作:
BOOST_FOREACH(boost::property_tree::ptree::value_type& framePair2, doc.get_child("content_scripts")){ jsFiles.push_back(framePair2.second.data());
我得到的是""
在 vector 字符串中。
我什至试过jsFiles.push_back(framePair2.second.get<std::string>("js"));
但它仍然不起作用。
我也试过其他方法都没有成功。
如果我能得到一个工作代码,我将不胜感激,因为我没有想法。
最佳答案
get<std::string>("js")
无法工作,因为 "js"
有一个数组值。
for(auto& e : pt.get_child("content_scripts"))
for(auto& r : e.second.get_child("js"))
std::cout << r.second.get_value<std::string>() << "\n";
应该做
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
std::string const sample = R"(
{
"background": {
"scripts": [ "name1.js", "name2.js", "name3.js" ]
},
"default_popup": "popup.html",
"default_title": "__MSG_name__",
"content_scripts": [ {
"all_frames": true,
"js": [ "name4.js", "name5.js", "name6.js" ],
"match_about_blank": true,
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_start"
}, {
"all_frames": true,
"js": [ "include.postload.js" ],
"match_about_blank": true,
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_end"
} ]
})";
using boost::property_tree::ptree;
namespace j = boost::property_tree::json_parser;
int main() {
std::istringstream iss(sample);
ptree pt;
j::read_json(iss, pt);
for(auto& e : pt.get_child("content_scripts"))
for(auto& r : e.second.get_child("js"))
std::cout << r.second.get_value<std::string>() << "\n";
}
打印
name4.js
name5.js
name6.js
include.postload.js
关于c++ - 使用 boost/property_tree 从具有多个元素/数组/子数组 C++ 的 json 文件中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27799086/