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_root
if (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;
}
4.8 C++ Boost 应用JSON解析库的更多相关文章
- Boost.JSON Boost的JSON解析库(1.75首发)
目录 目录 Boost的1.75版本新库 JSON库简介 JSON的简单使用 编码 最通用的方法 使用std::initializer_list json对象的输出 两种对比 解码 简单的解码 增加错 ...
- C++的Json解析库:jsoncpp和boost
C++的Json解析库:jsoncpp和boost - hzyong_c的专栏 - 博客频道 - CSDN.NET C++的Json解析库:jsoncpp和boost 分类: 网络编程 开源库 201 ...
- C++的Json解析库:jsoncpp和boost(转)
原文转自 http://blog.csdn.net/hzyong_c/article/details/7163589 JSON(JavaScript Object Notation)跟xml一样也是一 ...
- [转]C++的Json解析库:jsoncpp和boost
JSON(JavaScript Object Notation)跟xml一样也是一种数据交换格式,了解json请参考其官网http://json.org,本文不再对json做介绍,将重点介绍c++的j ...
- Tomjson - 一个"短小精悍"的 json 解析库
Tomjson,一个"短小精悍"的 json 解析库,tomjson使用Java语言编写,主要作用是把Java对象(JavaBean)序列化为json格式字符串,将json格式字符 ...
- fastjson是阿里巴巴的开源JSON解析库
fastjson的API十分简洁. String text = JSON.toJSONString(obj); //序列化 VO vo = JSON.parseObject("{...}&q ...
- python 中的json解析库
当一个json 数据很大的时候.load起来是很耗时的.python中常见的json解析库有cjson,simplesjson,json, 初步比较了一下, 对于loads来讲 simplejson ...
- Tomjson - json 解析库
Tomjson - 一个"短小精悍"的 json 解析库 Tomjson,一个"短小精悍"的 json 解析库,tomjson使用Java语言编写,主要作用是把 ...
- Android JSON解析库Gson和Fast-json的使用对比和图书列表小案例
Android JSON解析库Gson和Fast-json的使用对比和图书列表小案例 继上篇json解析,我用了原生的json解析,但是在有些情况下我们不得不承认,一些优秀的json解析框架确实十分的 ...
- 常用json解析库比较及选择 fastjson & gson
一.常用json解析库比较及选择 1.简介 fastjson和gson是目前比较常用的json解析库,并且现在我们项目代码中,也在使用这两个解析库. fastjson 是由阿里开发的,号称是处理jso ...
随机推荐
- Mongodb--索引(转载)
原文转载自:https://www.cnblogs.com/wyy1234/p/11032163.html 1 mongoDB索引的管理 本节介绍mongoDB中的索引,熟悉mysql/sqlserv ...
- POJ 1011 Sticks (DFS + 剪枝)
题目地址:http://poj.org/problem?id=1011 题目大意 给出n个小木棒,组合成若干长度最短棍子 解题思路 首先将木棒从大到小排序 dfs(k, l), k是还剩多少木棒没用, ...
- 【每日一题】14.Accumulation Degree(树形DP + 二次扫描)
补题链接:Here 一个树形水系,有 \(n\) 个结点,根结点称为源点,叶子结点称为汇点,每条边都有水量限制$C(x,y) \((\)x,y$ 为这条边的两个端点),源点单位时间流出的水量称为整个水 ...
- Spark SQL 字段血缘在 vivo 互联网的实践
作者:vivo互联网服务器团队-Hao Guangshi 一.背景 字段血缘是在表处理的过程中将字段的处理过程保留下来.为什么会需要字段血缘呢? 有了字段间的血缘关系,便可以知道数据的来源去处,以及字 ...
- Java 内存管理最佳实践
本文翻译自国外论坛 medium,原文地址:https://medium.com/@fullstacktips/best-practices-for-memory-management-in-java ...
- TortoiseSVN 中文手册下载
TortoiseSVN 链接:https://pan.baidu.com/s/1wAxZST9wKc_HebOrBiewjw 提取码:3gjq
- 机器学习-线性分类-SVM支持向量机算法-12
目录 1. 铺垫 感知器算法模型 2. SVM 算法思想 3. 硬分割SVM总结 支持向量机(Support Vector Machine, SVM)本身是一个二元分类算法,是对感知器算法模型的一种扩 ...
- 操作系统OS笔记2
操作系统OS笔记2 调度和死锁 调度简介 1. 调度的基本概念 2. 调度原则 调度算法 平均周转时间: 平均带权周转时间:周转时间/服务时间 1. 先来先服务调度算法(FCFS) 当在高级调度中采用 ...
- Redis 主从复制架构配置及原理
本文为博主原创,未经允许不得转载: 目录: 1. Redis 主从复制架构搭建 2. Redis 主从架构原理 3. Redis 断点续传 4. Jedis 连接 redis 主从架构一般配置一主多从 ...
- Introduction to DFT
服务器使用 登陆服务器:输入账号密码 打开terminal,保证至少一个terminal窗口是打开的 取消Linux操作系统的屏幕保护 设置Linux EDA工具配置 // 自定义环境变量设置 gvi ...