boost库读写json格式文件

发布时间:2024年01月17日

简介

????????本文通过boost库,版本为1.84。对json格式文件创建和解析的一个简单的Demo。生成过程中可能会用到库,需要指定库路径。本文通过单个key字段进行值的获取。也有其它方式比如key1.key2.key3.xxx获取值,每一个key代表一个节点。

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/json.hpp>
#include <iostream>

std::string write_json()
{
	boost::property_tree::ptree root;

	{
		boost::property_tree::ptree obj1;
		obj1.put("a", 1);
		obj1.put("b", 2);

		boost::property_tree::ptree obj1_array;

		for (int i = 0; i < 10; ++i)
		{
			boost::property_tree::ptree item;
			item.put("", i);
			obj1_array.push_back(std::make_pair("", item));
		}

		obj1.put_child("obj1_array", obj1_array);

		root.put_child("obj1", obj1);
	}

	{
		boost::property_tree::ptree obj2;

		for (int i = 50; i < 100; i += 10)
		{
			boost::property_tree::ptree item;
			item.put("", i);
			obj2.push_back(std::make_pair("", item));
		}

		root.put_child("obj2_array", obj2);
	}

	std::string file_name = "output.json";
	boost::property_tree::write_json(file_name, root);

	return file_name;
}

void read_json(std::string file_name)
{
	{
		boost::property_tree::ptree root;
		boost::property_tree::read_json(file_name, root);

		std::string _obj1_str = root.get<std::string>("obj1");
		if (_obj1_str.empty())
		{
			std::cout << "_obj1_str is empty." << std::endl;
		}
		else
		{
			std::cout << "_obj1_str is not emptly." << std::endl;
		}

		boost::property_tree::ptree _obj1_node = root.get_child("obj1");
		if (_obj1_node.empty())
		{
			std::cout << "_obj1_node is empty." << std::endl;
		}
		else
		{
			std::cout << "_obj1_node is not emptly." << std::endl;

			for (auto iter = _obj1_node.begin(); iter != _obj1_node.end(); ++iter)
			{
				std::string _key = iter->first;
				std::string _str_value = iter->second.get_value<std::string>(_key);
				if (!_str_value.empty())
				{
					std::cout << "first:" << _key << " " << iter->second.get_value<std::string>(_key) << std::endl;
				}
				else
				{
					for (const auto& item : iter->second)
					{
						std::cout << item.second.get_value<std::string>() << " ";
					}

					std::cout << std::endl;
				}
			}
		}
	}

#if 0
	{
		boost::property_tree::ptree pt;
		boost::property_tree::read_json(file_name, pt);

		std::cout << "obj1.a: " << pt.get<std::string>("obj1.a") << std::endl;
		std::cout << "obj1.b: " << pt.get<std::string>("obj1.b") << std::endl;
		std::cout << "obj1.obj1_array: ";
		for (const auto& item : pt.get_child("obj1.obj1_array")) {
			std::cout << item.second.get_value<std::string>() << " ";
		}
		std::cout << std::endl;

		std::cout << "obj2_array: ";
		for (const auto& item : pt.get_child("obj2_array")) {
			std::cout << item.second.get_value<std::string>() << " ";
		}
		std::cout << std::endl;
	}
#endif

}

int main()
{
	std::string file_name = write_json();

	read_json(file_name);

	return 0;
}

文章来源:https://blog.csdn.net/guoqignrus/article/details/135655589
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。