4.8 C++ Boost 应用JSON解析库

property_tree 是 Boost 库中的一个头文件库,用于处理和解析基于 XML、Json 或者 INFO 格式的数据。 property_tree 可以提供一个轻量级的、灵活的、基于二叉数的通用容器,可以处理包括简单值(如 int、float)和复杂数据结构(如结构体和嵌套容器)在内的各种数据类型。它可以解析数据文件到内存中,然后通过迭代器访问它们。

在 Boost 库中,property_tree 通常与 boost/property_tree/xml_parser.hpp、boost/property_tree/json_parser.hpp 或 boost/property_tree/info_parser.hpp 文件一起使用。这些文件分别提供了将 XML、JSON 或 INFO 格式数据解析为 property_tree 结构的功能。

首先我们需要自行创建一个测试config.json文件,后期的所有案例演示及应用都需要这个库的支持。

{"username": "lyshark","age": 24,"get_dict": { "username": "lyshark" },"get_list": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ],"user_data":[[ "192.168.1.1", "root", "123456" ],[ "192.168.1.2", "admin", "123456" ],[ "192.168.1.3", "mysql", "123456" ]],"user_dict":[{ "uid": 1001, "uname": "admin" },{ "uid": 1002, "uname": "lyshark" },{ "uid": 1003, "uname": "root" }],"get_root":[{"firstName": "admin","lastName": "JackWang","email": "admin@lyshark.com"},{"firstName": "lyshark","lastName": "xusong","email": "me@lyshark.com"}],"get_my_list":{"get_uint": "[1,2,3,4,5,6,7,8,9,0]", "get_string": "['admin','lyshark','root']"}
}

8.1 解析单个节点

代码中使用了 Boost C++ 库中的 property_tree 和 json_parser 来解析 JSON 文件。它的主要功能是读取指定路径下的 “c://config.json” 文件,然后获取其中的用户名和年龄信息(如果存在的话),并将它们输出到控制台。

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>using namespace std;int main(int argc, char* argv[])
{boost::property_tree::ptree ptr;boost::property_tree::read_json("c://config.json", ptr);cout << "是否存在: " << ptr.count("username") << endl;if (ptr.count("username") != 0){std::string username = ptr.get<std::string>("username");std::cout << "用户名: " << username << std::endl;}if (ptr.count("age") != 0){int age = ptr.get<int>("age");std::cout << "年龄: " << age << std::endl;}system("pause");return 0;
}

8.2 解析单个列表

代码中使用了 Boost C++ 库中的 property_tree 和 json_parser 来解析 JSON 文件。它的功能是读取指定路径下的 “c://config.json” 文件,并提取名为 “get_list” 的字段的值,并将其输出到控制台。

#include <iostream>
#include <vector>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>using namespace std;void GetJson(std::string &filePath)
{boost::property_tree::ptree ptr;std::vector<std::string> item;boost::property_tree::read_json(filePath, ptr);// 先判断是否存在字段if (ptr.count("get_list") == 1){boost::property_tree::ptree pChild = ptr.get_child("get_list");for (auto pos = pChild.begin(); pos != pChild.end(); ++pos){// 迭代循环,将元素房补vector列表中std::string list = pos->second.get_value<string>();item.push_back(list);}}// 迭代输出vector中的数据for (auto x = item.begin(); x != item.end(); ++x){cout << *x << endl;}
}int main(int argc, char* argv[])
{GetJson(std::string("c://config.json"));system("pause");return 0;
}

8.3 解析嵌套列表

这段代码依然使用了 Boost C++ 库中的 property_tree 和 json_parser 来解析 JSON 文件。它的功能是读取指定路径下的 “c://config.json” 文件,并提取名为 “user_data” 的字段的第二列数据,并将其输出到控制台。

#include <iostream>
#include <vector>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>using namespace std;void GetJson(std::string &filePath)
{boost::property_tree::ptree ptr;boost::property_tree::read_json(filePath, ptr);std::vector<std::string> item;for (auto& root_child : ptr.get_child("user_data")){int count = 1;for (auto& x : root_child.second){// count 用于指定需要那一列的记录if (count == 2){std::string sub_data = x.second.get_value<std::string>();cout << "输出元素: " << sub_data << endl;item.push_back(sub_data);}count++;}}// 迭代输出vector中的数据for (auto x = item.begin(); x != item.end(); ++x){cout << *x << endl;}
}int main(int argc, char* argv[])
{GetJson(std::string("c://config.json"));system("pause");return 0;
}

8.4 解析多层字典

代码同样使用了 Boost C++ 库中的 property_tree 和 json_parser 来解析 JSON 文件。它的功能是读取指定路径下的 “c://config.json” 文件,并提取名为 “get_dict” 和 “user_dict” 的字段数据,并将其输出到控制台。

#include <iostream>
#include <vector>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>using namespace std;void GetJson(std::string &filePath)
{boost::property_tree::ptree ptr;boost::property_tree::read_json(filePath, ptr);// 解析单一字典std::string username = ptr.get_child("get_dict").get<std::string>("username");cout << "姓名: " << username << endl;// 解析多层字典boost::property_tree::ptree root_ptr, item;root_ptr = ptr.get_child("user_dict");// 输出第二层for (boost::property_tree::ptree::iterator it = root_ptr.begin(); it != root_ptr.end(); ++it){item = it->second;cout << "UID: " << item.get<int>("uid") << " 姓名: " << item.get<string>("uname") << endl;}
}int main(int argc, char* argv[])
{GetJson(std::string("c://config.json"));system("pause");return 0;
}

第二种方式,通过多次迭代解析多层字典,并将字典中的特定value放入到vector容器内。

#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>using namespace std;
using namespace boost;
using namespace boost::property_tree;int main(int argc, char *argv[])
{boost::property_tree::ptree ptr;boost::property_tree::read_json("C://config.json", ptr);// 判断是否存在get_rootif (ptr.count("get_root") == 1){std::vector<string> vecStr;std::string get_first_name;boost::property_tree::ptree p1, p2;// 读取到根节点p1 = ptr.get_child("get_root");// 循环枚举for (ptree::iterator it = p1.begin(); it != p1.end(); ++it){// 获取到字典的value值p2 = it->second;get_first_name = p2.get<string>("firstName");// 将获取到的value转换为vector容器vecStr.push_back(get_first_name);}// 输出容器中的内容for (int x = 0; x < vecStr.size(); x++){std::cout << vecStr[x] << std::endl;}}std::system("pause");return 0;
}

8.5 写出JSON文件

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>using namespace std;// 初始化字符串
bool InitJSON()
{string str = "{\"uuid\":1001,\"Student\":[{\"Name\":\"admin\"},{\"Name\":\"lyshark\"}]}";stringstream stream(str);boost::property_tree::ptree strTree;try{read_json(stream, strTree);}catch (boost::property_tree::ptree_error & e) {return false;}write_json("c://config.json", strTree);return true;
}// 初始化列表
void InitArray()
{boost::property_tree::ptree ptr;boost::property_tree::ptree children;boost::property_tree::ptree child1, child2, child3;child1.put("", 1);child2.put("", 2);child3.put("", 3);children.push_back(std::make_pair("", child1));children.push_back(std::make_pair("", child2));children.push_back(std::make_pair("", child3));ptr.add_child("MyArray", children);write_json("c://Array.json", ptr);
}// 初始化字典
void InitDict()
{boost::property_tree::ptree ptr;boost::property_tree::ptree children;boost::property_tree::ptree child1, child2, child3;child1.put("childkeyA", 1);child1.put("childkeyB", 2);child2.put("childkeyA", 3);child2.put("childkeyB", 4);child3.put("childkeyA", 5);child3.put("childkeyB", 6);children.push_back(std::make_pair("", child1));children.push_back(std::make_pair("", child2));children.push_back(std::make_pair("", child3));ptr.put("testkey", "testvalue");ptr.add_child("MyArray", children);write_json("c://MyDict.json", ptr);
}int main(int argc, char* argv[])
{InitArray();InitDict();InitJSON();boost::property_tree::ptree ptr;boost::property_tree::read_json("c://config.json", ptr);// 修改uuid字段if (ptr.count("uuid") != 0){ptr.put("uuid", 10002);}boost::property_tree::write_json("c://config.json", ptr);system("pause");return 0;
}

8.6 自定义结构解析

#include <iostream>
#include <string>
#include <vector>
#include <boost/assign.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>using namespace std;
using namespace boost;
using namespace boost::property_tree;// 将整数转为int容器
std::vector<int> JsonIntToVector(std::string string_ptr)
{std::vector<std::string> vect;// 去掉里面的[]符号std::string item = boost::trim_copy_if(string_ptr, (boost::is_any_of("[") || boost::is_any_of("]")));boost::split(vect, item, boost::is_any_of(",,"), boost::token_compress_on);std::vector<int> ref;for (auto each : vect){ref.push_back(boost::lexical_cast<int>(each));}return ref;
}// 将字符串列表转为string容器
std::vector<std::string> JsonStringToVector(std::string string_ptr)
{std::vector<std::string> ref;std::vector<std::string> vect;std::string item = boost::trim_copy_if(string_ptr, (boost::is_any_of("[") || boost::is_any_of("]")));boost::split(vect, item, boost::is_any_of(",,"), boost::token_compress_on);for (auto each : vect){// 去掉单引号std::string ea = boost::trim_copy_if(each, (boost::is_any_of("'") || boost::is_any_of("\"")));ref.push_back(ea);}return ref;
}int main(int argc, char *argv[])
{boost::property_tree::ptree ptr;boost::property_tree::read_json("./config.json", ptr);// 输出特殊的整数std::string ustring = ptr.get_child("get_my_list").get<std::string>("get_uint");std::vector<int> ref_int = JsonIntToVector(ustring);for (int x = 0; x < ref_int.size(); x++){std::cout << "输出整数: " << ref_int[x] << std::endl;}// 输出特殊的字符串std::string ustring1 = ptr.get_child("get_my_list").get<std::string>("get_string");std::vector<std::string> ref_string = JsonStringToVector(ustring1);for (int x = 0; x < ref_string.size(); x++){std::cout << "输出字符串: " << ref_string[x] << std::endl;}std::system("pause");return 0;
}

本文作者: 王瑞
本文链接: https://www.lyshark.com/post/ea32fbc2.html
版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/51600.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++最易读手撸神经网络两隐藏层(任意Nodes每层)梯度下降230820a

这是史上最简单、清晰&#xff0c;最易读的…… C语言编写的 带正向传播、反向传播(Forward ……和Back Propagation&#xff09;……任意Nodes数的人工神经元神经网络……。 大一学生、甚至中学生可以读懂。 适合于&#xff0c;没学过高数的程序员……照猫画虎编写人工智能、…

矿井水处理技术离子交换树脂法

矿井水除氟的要求一般是处理后水中的含氟量≤1.0mg/L。氟化物含量高的原水往往呈偏碱性&#xff0c;pH值常大于7.5。利用阴离子交换树脂上的可交换阴离子&#xff0c;去交换水中的氟离子&#xff0c;达到除氟目的。氟离子的选择交换性较大&#xff0c;树脂上的SO42-、Cl-等阴离…

卷积过程详细讲解

1&#xff1a;单通道卷积 以单通道卷积为例&#xff0c;输入为&#xff08;1,5,5&#xff09;&#xff0c;分别表示1个通道&#xff0c;宽为5&#xff0c;高为5。假设卷积核大小为3x3&#xff0c;padding0&#xff0c;stride1。 卷积过程如下&#xff1a; 相应的卷积核不断…

企微配置回调服务

1、企微配置可信域名 2、企微获取成员userID 3、企微获取用户敏感数据 4、企微配置回调服务 文章目录 一、简介1、概述2、相关文档地址 二、企微配置消息服务器1、配置消息接收参数2、参数解析3、参数拼接规则 三、代码编写—使用已有库1、代码下载2、代码修改3、服务代码编写 …

基于swing的超市信息管理系统java jsp仓库进销存mysql源代码

本项目为前几天收费帮学妹做的一个项目&#xff0c;Java EE JSP项目&#xff0c;在工作环境中基本使用不到&#xff0c;但是很多学校把这个当作编程入门的项目来做&#xff0c;故分享出本项目供初学者参考。 一、项目描述 基于swing的超市信息管理系统 系统有1权限&#xff1…

Linux驱动开发(Day5)

思维导图&#xff1a; 不同设备号文件绑定&#xff1a;

回归预测 | MATLAB实现SA-ELM模拟退火算法优化极限学习机多输入单输出回归预测(多指标,多图)

回归预测 | MATLAB实现SA-ELM模拟退火算法优化极限学习机多输入单输出回归预测&#xff08;多指标&#xff0c;多图&#xff09; 目录 回归预测 | MATLAB实现SA-ELM模拟退火算法优化极限学习机多输入单输出回归预测&#xff08;多指标&#xff0c;多图&#xff09;效果一览基本…

ElasticSearch-集成ik分词器

本文已收录于专栏 《中间件合集》 目录 背景介绍版本选择优势说明集成过程1.下载安装包2.解压安装包3.重启ElasticSearch服务3.1通过ps -ef | grep elastic查看正在启动的es进程号3.2使用kill -9 xxx 杀死进程3.3使用 ./elasticsearch 启动es服务 分词测试细粒度分词方式分词请…

CTFshow 限时活动 红包挑战9 详细题解

CTFshow红包挑战9 题目源码开源了。源码如下&#xff1a; common.php <?phpclass user{public $id;public $username;private $password;public function __toString(){return $this->username;}}class cookie_helper{private $secret "*************"; /…

【Java架构-包管理工具】-Maven私服搭建-Nexus(三)

本文摘要 Maven作为Java后端使用频率非常高的一款依赖管理工具&#xff0c;在此咱们由浅入深&#xff0c;分三篇文章&#xff08;Maven基础、Maven进阶、私服搭建&#xff09;来深入学习Maven&#xff0c;此篇为开篇主要介绍Maven私服搭建-Nexus 文章目录 本文摘要1. Nexus安装…

【multimaster_fkie】多 ros master core 通信库,不配置主从机进行 ros 多机通信

1. 简介 多个 ros 系统之间可以通过配置 ros 主从机实现互相通信&#xff0c;但有的场景每个 ros 系统都需要运行 rosmaster/roscore &#xff0c;这种情况下就需要使用 multimaster_fkie 库来实现 ros 通信。 Github&#xff1a;https://github.com/fkie/multimaster_fkie RO…

本地搭建CFimagehost私人图床【公网远程访问】

文章目录 1.前言2. CFImagehost网站搭建2.1 CFImagehost下载和安装2.2 CFImagehost网页测试2.3 cpolar的安装和注册 3.本地网页发布3.1 Cpolar临时数据隧道3.2 Cpolar稳定隧道&#xff08;云端设置&#xff09;3.3.Cpolar稳定隧道&#xff08;本地设置&#xff09; 4.公网访问测…

Redis数据结构之Set

Set 类型是一个无序并唯一的键值集合&#xff0c;它的存储顺序不会按照插入的先后顺序进行存储。Redis 中集合是通过哈希表实现的&#xff0c;所以添加&#xff0c;删除&#xff0c;查找的复杂度都是 O(1)。相对于列表&#xff0c;集合也有两个特点&#xff1a;无序、不可重复 …

js reverse实现数据的倒序

2023.8.25今天我学习了如何在数组顺序进行倒序排列&#xff0c;如&#xff1a; 原数组为&#xff1a; 我们只需要对数组使用reverse()方法 let demo [{id: 1, name: 一号},{id: 2, name: 二号},{id: 3, name: 三号},]demo.reverse()console.log(demo) 扩展&#xff1a; 当我…

jmeter入门:接口压力测试全解析

一.对接口压力测试 1.配置 1.添加线程组&#xff08;参数上文有解释 这里不介绍&#xff09; 2.添加取样器 不用解释一看就知道填什么。。。 3.添加头信息&#xff08;否则请求头对不上&#xff09; 也不用解释。。。 4.配置监听器 可以尝试使用这几个监听器。 2.聚合结果…

Tushare入门小册

Tushare入门小册 一、Tushare平台介绍 Pro版数据更稳定质量更好了&#xff0c;我们提供的不再是直接从互联网抓取&#xff0c;而是通过社区的采集和整理存入数据库经过质量控制后再提供给用户。但Pro依然是个开放的&#xff0c;免费的平台&#xff0c;不带任何商业性质和目的…

什么是服务端渲染?前后端分离的优点和缺点?

一.概念 服务端渲染简单点就是服务端直接返回给客户端一个完整的页面&#xff0c;也就是一个完整的html页面&#xff0c;这个页面上已经有数据了。说到这里你可能会觉得后端怎么写页面啊&#xff0c;而且服务端返回页面不是加载更慢吗&#xff1f;错了&#xff0c;因为我们现在…

4.网络设计与redis、memcached、nginx组件(一)

网络组件系列文章目录 第四章 网络设计与redis、memcached、nginx组件 文章目录 网络组件系列文章目录文章的思维导图前言一、网络相关的问题&#xff0c;网络开发中要处理那些问题&#xff1f;网络操作IO连接建立连接断开消息到达消息发送网络操作IO特性 二、网络中IO检测IO函…

VR、AR、MR 傻傻分不清楚?区别的底层逻辑?

VR是一种能够制作虚拟物体并与人互动的基础技术。它与操作者所处的环境无关。AR可以让在特定位置出现或消失。MR可以让虚拟物体与真实物体进行互动。 AR和MR的大部分应用场景都是随机的&#xff0c;所以硬件基本都采用手机和眼镜。提升了便携性。牺牲了性能。这就导致了AR与MR…

基于Springboot+vue的宠物服务管理系统——LW模板

摘 要 21世纪的今天&#xff0c;随着人类生活从低层次不断向高层次跃进&#xff0c;人类和宠物的关系已经密不可分。人们生活水平的进步进而带来了宠物生活水平的进步&#xff0c;因此对于宠物的管理也愈发的丰富起来&#xff0c;宠物的膳食安排&#xff0c;宠物的医疗安排等都…