Boost属性树不能在一个文件中读取多个json数据

boost property tree cannot read multiple json data in one file

本文关键字:文件 读取 数据 json 一个 不能 Boost 属性      更新时间:2023-10-16

我真的需要得到帮助来解决我的问题。我使用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;

我希望这对你有帮助