Boost属性树不能在一个文件中读取多个json数据
boost property tree cannot read multiple json data in one file
我真的需要得到帮助来解决我的问题。我使用boost属性树来解析存储在json文件中的推特消息。所有消息都保存在一个json文件中,我需要逐个解析。
这是保存在一个文件中的twitter json数据。它有3个不同的信息。(下面扣除的消息仅用于测试)
{"id":593393012970926082,"in_reply_to_status_id":1,"user":{"id":2292380240,"followers_count":2},"retweet_count":0}
{"id":654878454684687878,"in_reply_to_status_id":7,"user":{"id":2292380241,"followers_count":4},"retweet_count":5}
{"id":123487894154878414,"in_reply_to_status_id":343,"user":{"id":2292380242,"followers_count":773},"retweet_count":654}
这里是我的c++代码解析的消息,使用属性树。
#include <boost/property_tree/json_parser.hpp>
using namespace std;
using namespace boost::property_tree;
string jsonfile = "./twitter.json";
int main()
{
ptree pt;
read_json( jsonfile, pt );
cout<<"in_reply_to_status_id: "<<pt.get("in_reply_to_status_id",0)<<"n";
}
我想从文件中获取所有in_reply_to_status_id值。现在它只打印第一行的值。结果是打印跟踪。
in_reply_to_status_id: 1
我想要得到下面所有的值。
in_reply_to_status_id: 1
in_reply_to_status_id: 7
in_reply_to_status_id: 343
如何从文件中获取所有值?请帮帮我。非常感谢。
您应该有正确的json文件,例如如下
[
{"id":593393012970926082,"in_reply_to_status_id":1,"user":{"id":2292380240,"followers_count":2},"retweet_count":0},
{"id":654878454684687878,"in_reply_to_status_id":7,"user":{"id":2292380241,"followers_count":4},"retweet_count":5},
{"id":123487894154878414,"in_reply_to_status_id":343,"user":{"id":2292380242,"followers_count":773},"retweet_count":654}
]
代码应该是这样的
for (const auto& p : pt)
{
cout << p.second.get("in_reply_to_status_id",0) << endl;
}
可以用BOOST_FOREACH
代替range-based for
,例如
BOOST_FOREACH(const ptree::value_type& p, pt)
您可以看到我的例子,首先您应该获得子树,然后解析它。我的代码:
string str = "{"key":[{"id":1}, {"id":2}]}";
stringstream ss(str);
boost::property_tree::ptree parser, child;
boost::property_tree::json_parser::read_json(ss, parser);
child = parser.get_child("key");
for(auto& p : child)
cout << p.second.get<uint32_t>("id") << endl;
我希望这对你有帮助
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量