Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple example of parsing and consuming JSON array with boost::property_tree
#ifdef _MSC_VER
#include <boost/config/compiler/visualc.hpp>
#endif
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <cassert>
#include <exception>
#include <iostream>
#include <sstream>
#include <string>
int main()
{
try
{
std::stringstream ss;
ss << "{ \"root\": { \"values\": [1, 2, 3, 4, 5 ] } }";
boost::property_tree::ptree pt;
boost::property_tree::read_json(ss, pt);
BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pt.get_child("root.values"))
{
assert(v.first.empty()); // array elements have no names
std::cout << v.second.data() << std::endl;
}
return EXIT_SUCCESS;
}
catch (std::exception const& e)
{
std::cerr << e.what() << std::endl;
}
return EXIT_FAILURE;
}
@santoshkamblecpp

This comment has been minimized.

Copy link

@santoshkamblecpp santoshkamblecpp commented Oct 9, 2020

Can you show the way to generate this format { "root": { "values": [1, 2, 3, 4, 5 ] } }
using same boost tree json library. ?

Because boost tree json , converts number/values to string forms. So I wanted to know how we can generate above json.

@mloskot

This comment has been minimized.

Copy link
Owner Author

@mloskot mloskot commented Oct 9, 2020

@santoshkamblecpp The https://www.boost.org/doc/libs/1_74_0/doc/html/property_tree/parsers.html says

JSON values are mapped to nodes containing the value. However, all type information is lost; numbers, as well as the literals "null", "true" and "false" are simply mapped to their string form.

Thus, write your own serialising function (or search the StackOverflow) or use different library (e.g. https://github.com/boostorg/json)

@santoshkamblecpp

This comment has been minimized.

Copy link

@santoshkamblecpp santoshkamblecpp commented Oct 9, 2020

@santoshkamblecpp The https://www.boost.org/doc/libs/1_74_0/doc/html/property_tree/parsers.html says

JSON values are mapped to nodes containing the value. However, all type information is lost; numbers, as well as the literals "null", "true" and "false" are simply mapped to their string form.

Thus, write your own serialising function (or search the StackOverflow) or use different library (e.g. https://github.com/boostorg/json)

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.