0

I have data like this

{"json": "a_string", "data": [0,1,2,3,4]}

I’m trying to access any specific element of "data" "directly".

Inspired by the approach of iterating over the elements, as described here, I used the iterator to get the first element.

root.get_child("data").begin()->second.get_value<int>();

But I am quite sure there should be an option to just say something like .get(0) or .get(1), but this call needs the knowledge I am operating on something like a list / vector.

Here is my code:

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

using namespace std;
using namespace boost::property_tree;

int main(int argc, char** argv)
{
    string str("{\"json\": \"a_string\", \"data\": [0,1,2,3,4]}");
    stringstream ss(str);
    ptree root;
    read_json(ss,root);

    int first_value = root.get_child("data").begin()->second.get_value<int>();

    cout << first_value << endl;
    getc(stdin);
}
Bambino
  • 405
  • 4
  • 15
  • I linked to the question you are referring to in my question. It does not answer my question though. I want to access the elements directly, not iterate over them. – Bambino Nov 16 '16 at 14:33
  • 1
    Is it a random access iterator? If yes, just add the offset. If not, copy it into your own container and use that. – LogicStuff Nov 16 '16 at 14:35
  • 1
    Okay, your proposal helped me out a bit. If I save the iterator with "auto it = root.get_child("data").begin();", then "std::advance(it,3);", I get the desired value when using it. But the question how to access the value "directly" remains. Isn't there an easy way? – Bambino Nov 16 '16 at 14:52

0 Answers0