C++使用JSON文件boost程序选项
问题描述:
这是可能的升压方案选择库:http://www.boost.org/doc/libs/1_64_0/doc/html/program_options.htmlC++使用JSON文件boost程序选项
读取JSON格式的文件作为此输入文件?
或者,如果我有像文件JSON一些配置,我需要解析它自己,与例如:http://www.boost.org/doc/libs/1_64_0/doc/html/property_tree.html
答
我遇到了同样的问题。下面是我实现的JSON解析器为program_options库的基础上,property_tree:
template <class charT> void parseChildren(std::string prefix, boost::property_tree::ptree& tree, boost::program_options::parsed_options& options)
{
if (tree.size() == 0)
{
//cut first dot
std::basic_string<charT> name = prefix.substr(1);
std::basic_string<charT> value = tree.data();
boost::program_options::basic_option<charT> opt;
opt.string_key = name;
opt.value.push_back(value);
opt.unregistered = (options.description->find_nothrow(name, false) == nullptr);
opt.position_key = -1;
options.options.push_back(opt);
}
else
{
for (auto it = tree.begin(); it != tree.end(); ++it)
{
parseChildren<charT>(prefix + "." + it->first, it->second, options);
}
}
}
template <class charT>
void parseJsonOptions(std::basic_istream<charT>& is, boost::program_options::parsed_options& options)
{
boost::property_tree::basic_ptree<std::basic_string<charT>, std::basic_string<charT>> pt;
boost::property_tree::read_json(is, pt);
parseChildren<charT>(std::basic_string<charT>(), pt, options);
}
template <class charT>
boost::program_options::basic_parsed_options<charT> parse_json_config_file(std::basic_istream<charT>& is, const boost::program_options::options_description& desc, bool allow_unregistered = false)
{
// do any option check here
boost::program_options::parsed_options result(&desc);
parseJsonOptions(is, result);
return boost::program_options::basic_parsed_options<charT>(result);
}
这样使用它:
po::variables_map vm;
std::ifstream configFileStream(configFilePath_.generic_string());
store(parse_json_config_file(configFileStream, algorithmsDesc_), vm);
notify(vm);
答
这是可能的升压方案选择库: http://www.boost.org/doc/libs/1_64_0/doc/html/program_options.html
阅读json格式化文件作为输入文件在这里?
没有,但你可以,如果你写一个它
或者,如果我有像文件JSON一些配置,我需要解析它自己, 有例如: http://www.boost.org/doc/libs/1_64_0/doc/html/property_tree.html
您可以。一定要检查limitations。另外,要小心诸如“json like”之类的东西。有可能是任何非标准的JSON都会破坏解析器,所以如果它不是标准的,你可能想手动处理它。
不错的工作。 +1实际上提出了一个实现。这应该作为文档中的一个示例 – sehe