boost库读写json格式文件

简介

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

#include 
#include 
#include 
#include 

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("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(_key);
				if (!_str_value.empty())
				{
					std::cout << "first:" << _key << " " << iter->second.get_value(_key) << std::endl;
				}
				else
				{
					for (const auto& item : iter->second)
					{
						std::cout << item.second.get_value() << " ";
					}

					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("obj1.a") << std::endl;
		std::cout << "obj1.b: " << pt.get("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::cout << std::endl;

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

}

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

	read_json(file_name);

	return 0;
}

你可能感兴趣的:(C/C++,json,c++)