C ++ boost分析动态生成的json字符串(不是文件) [英] C++ boost parse dynamically generated json string (not a file)

查看:198
本文介绍了C ++ boost分析动态生成的json字符串(不是文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个最小的示例,以读取通过boost命令行arg传递的json字符串.我是C ++的新手,并且对我很有帮助.

I am trying to make a minimal example of reading a json string that is passed as a command line arg with boost. I am very new to C++ and to boost.

我的代码是:

int main (int argc, char ** argv)
{
  boost::property_tree::ptree pt;
  boost::property_tree::read_json(argv[1], pt);
  cout << pt.get<std::string>("foo");
}

我这样称呼

./myprog "{ \"foo\" : \"bar\" }"

但是我收到无法打开文件错误".如何获得增强以读取std :: string或char *而不是文件?

But I get a 'cannot open file error'. How do I get boost to read a std::string or a char* rather than a file?

谢谢

推荐答案

您可以做的是将字符读入字符串流,然后将其传递给read_json.

What you can do is read the characters into a string stream, and then pass that to read_json.

#include <sstream>
#include <iostream>

#include <boost/property_tree/json_parser.hpp>

int main (int argc, char ** argv)
{
  std::stringstream ss;
  ss << argv[1];

  boost::property_tree::ptree pt;
  boost::property_tree::read_json(ss, pt);
  std::cout << pt.get<std::string>("foo") << std::endl;
}

输出

bar

这篇关于C ++ boost分析动态生成的json字符串(不是文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆