Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve content from JSON in C++ using Boost library

Tags:

c++

json

boost

This is my JSON file.

{
    "found":3,
    "totalNumPages":1,
    "pageNum":1,
    "results":
    [
        {
            "POSTAL":"000000"
        },
        {
            "POSTAL":"111111"
        },
        {
            "POSTAL":"222222"
        }
    ]
}

Here is the C++ code.

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

int main()
{
    // Short alias for this namespace
    namespace pt = boost::property_tree;

    // Create a root
    pt::ptree root;

    // Load the json file in this ptree
    pt::read_json("filename.json", root);

    std::vector< std::pair<std::string, std::string> > results; 
    // Iterator over all results
    for (pt::ptree::value_type &result : root.get_child("results"))
    {
        // Get the label of the node
        std::string label = result.first;
        // Get the content of the node
        std::string content = result.second.data();
        results.push_back(std::make_pair(label, content));
        cout << result.second.data();
    }
}

I need to get each set of child value reside in the parent ("results") but it prints out blank. I have tried using

root.get_child("results.POSTAL") 

but because of the square bracket, it will throw error. Any advice?

like image 406
TicTacToe Avatar asked Oct 25 '25 08:10

TicTacToe


1 Answers

Arrays in Boost Property Tree are represented as objects with multiple unnamed properties.

Therefore, just loop over them:

Live On Coliru

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

int main()
{
    namespace pt = boost::property_tree;
    pt::ptree root;
    pt::read_json("filename.json", root);

    std::vector< std::pair<std::string, std::string> > results; 
    // Iterator over all results
    for (pt::ptree::value_type &result : root.get_child("results."))
        for (pt::ptree::value_type &field : result.second)
            results.push_back(std::make_pair(field.first, field.second.data()));

    for (auto& p : results)
        std::cout << p.first << ": " << p.second << "\n";
}

Prints

POSTAL: 000000
POSTAL: 111111
POSTAL: 222222
like image 89
sehe Avatar answered Oct 27 '25 23:10

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!