3

How can I get data from JSON with array as root node by using Boost.PropertyTree?

[
  {
      "ID": "cc7c3e83-9b94-4fb2-aaa3-9da458c976f7",
      "Type": "VM"
  }
]
Filburt
  • 17,626
  • 12
  • 64
  • 115
likern
  • 3,744
  • 5
  • 36
  • 47

1 Answers1

2

The array elements are just values with a key named "" for property tree:

for (auto& array_element : pt) {
    for (auto& property : array_element.second) {
        std::cout << property.first << " = " << property.second.get_value<std::string>() << "\n";
    }
}

Prints

ID = cc7c3e83-9b94-4fb2-aaa3-9da458c976f7
Type = VM

Live On Coliru

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

using namespace boost::property_tree;

int main()
{
    std::istringstream iss(R"([
    {
        "ID": "cc7c3e83-9b94-4fb2-aaa3-9da458c976f7",
        "Type": "VM"
    }
    ]
    )");

    ptree pt;
    json_parser::read_json(iss, pt);

    for (auto& array_element : pt) {
        for (auto& property : array_element.second) {
            std::cout << property.first << " = " << property.second.get_value<std::string>() << "\n";
        }
    }
}
sehe
  • 374,641
  • 47
  • 450
  • 633
  • As I see I can't use something like in documentation `pt.get("key");`, because root array doesn't have key and I have to use iteration over array, am I right? – likern Nov 15 '14 at 13:26
  • That's possible. This is just the first thing I tried. It seems likely that this restriction exists: how would you handle repeated keys anyways - let alone repeated "" keys :) – sehe Nov 15 '14 at 14:04
  • @sehe is it possible to find out the child in a JSON using boost ptree ? – CocoCrisp Mar 06 '17 at 11:03
  • @Milind ? perhaps you can ask a (clearer) question on the main site. – sehe Mar 06 '17 at 12:40