0

I'm trying to parse a std::string JSON string with this code:

        std::string ss = "{ \"id\" : \"abc123\", \"number\" : \"0123456789\", \"somelist\" : [{ \"timestamp\" : \"May 1, 2015\" , \"data\" : { \"description\" : \"some description\", \"value\" : \"100.000000\" } }] }";

        ptree pt2;
        std::istringstream is(ss);
        read_json(is, pt2);
        std::string _id = pt2.get<std::string>("id");
        std::string _number = pt2.get<std::string>("number");
        std::string _list = pt2.get<std::string>("somelist"); 


        for (auto& e : pt2.get_child("somelist")) {
            std::cout << "timestamp: " << e.second.get<std::string>("timestamp") << "\n";
            for (auto& e1 : pt2.get_child("data")){ // not working
                std::cout << "description: " << e1.second.get<std::string>("description") << "\n";
                std::cout << "value: " << e1.second.get<std::string>("amount") << "\n";
            }
        }

Although my target is not to print the child items (nor convert the JSON string into C++ array). The code above does not work.

I want to know how to get the value of data not as array or something, just as string like this [{ "timestamp" : "May 1, 2015" , "data" : { "description" : "some description", "value" : "100.000000" } }]

Just need the JSON Array as-is as std::string

3
  • Have you tried something like std::stringstream ss; write_json(ss, pt2.get_child("data")); ? In your case, .get_child("somelist").get_child("data") or e.get_child("data").. depending where in your code you want to use it. Commented Jul 10, 2015 at 19:47
  • doing write_json(ss, pt2.get_child("data")); causes no such node error :-) Commented Jul 10, 2015 at 19:53
  • Huh? Just tried here and works as a charm. After the printing timestamp and added those lines: ptree d = e.second.get_child("data"); std::stringstream s1; write_json(s1, d); std::cout <<s1.str << std::endl;. Demo Link Commented Jul 10, 2015 at 20:40

1 Answer 1

1

boost/property_tree/json_parser.hpp implements write_json, which is, as you would expect, the inverse of read_json. Since ptree stores arrays as objects with an empty key, to achieve the representation you want, you would loop over the top-level ptrees in pt2.get_child("somelist"), call write_json on each of them and format these representations as you wish.

for(auto const& node : pt2.get_child("somelist"))
 write_json(std::cout, node.second);

Coliru Demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.