c++ ptree判断是否存在节点_新人报道献礼:关于boost property_tree的一些探讨

本人最近工作中要用到c++解析json的方法,故在网上查了不少文章进行学习。

先发点牢骚:找了很多文章,但感觉多数内容雷同,深度不够,缺乏自己的分析和稍微深入一些的见解。

然后要感谢下面这2篇文章的作者:

http://www.voidcn.com/article/p-smrzeuyb-bud.html

http://einverne.github.io/post/2016/01/boost-learning-note-7.html

花了大约2-3个小时的时间仔细学习了一下,改写出了下面的一段测试代码:

#include

#include

#include

using namespace boost::property_tree;

using namespace std;

void test1_2(){

//http://www.voidcn.com/article/p-smrzeuyb-bud.html

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"

} ]

})";

//printf("sample=%s\n",sample.c_str());

ptree pt;

stringstream stream1(sample);

read_json(stream1,pt);

struct temp_fxn1 {

//ref: basic_ptree public member functions

static int ptree_type(const ptree &pt){

if(pt.size()>0){

if(pt.begin()->first==""){

return 1;//array

}else{

return 2;//object

}

}else{

return 0;//leaf

}

}

};

//遍历

//for(auto &e : pt){

//故意这样写:ref http://einverne.github.io/post/2016/01/boost-learning-note-7.html

for(boost::property_tree::ptree::iterator it = pt.begin(); it != pt.end(); ++it){

auto &e=*it;

printf("===>\n");

std::cout << e.first << ',' << e.second.get_value<:string>()<

printf("~~~~>\n");

for(auto &c : e.second){

std::cout << c.first << "\n";

}

}

}

这段代码实现了解析任意json字符串的功能(不包括出错处理),其中temp_fxn1::ptree_type()函数用于判断一个ptree节点类型。

注1:在解析json str是,只要str本身符合json的预压就可以生成一颗ptree,并不需要知道json str里面具体有哪些字段。这是多数文章未解决的问题。

注2:本人不喜欢 for(auto &e : pt){...}以及 BOOST_FOREACH 这样的写法。

致c++初学者:建议仔细走读一下这段程序,本人虽然水平不高,但还是花了不少心思的。这段代码里面包含了不少c++的知识点。

本人从事c++编码20余年,居然不知道R"..."这样的写法,实在惭愧。看来大家在一起交流是很重要的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值