4

I have a json that looks like this:

{"field":{"val1":25, "val2":48, "name1":"qqd"}}

When I do a verification of the received json has the specific fields like this:

std::size_t fcnt = pt.count("field");
std::size_t val1cnt = pt.count("field.val1");
std::size_t val2cnt = pt.count("field.val2");
std::size_t nm1cnt = pt.count("field.name1");
std::cout << fcnt << val1cnt << val2cnt << nm1cnt << std::endl; // this is just for testing
if (fcnt != 1 || val1cnt != 1 || val2cnt != 1 || nm1cnt !=1)
  throw BadJSONFormatException();

I get always the exception and the values printed are: 1000. Why? count does not work like this?

manlio
  • 18,345
  • 14
  • 76
  • 126
sop
  • 3,445
  • 8
  • 41
  • 84

1 Answers1

7

The docs says: "Count the number of direct children with the given key."

In other words, the string you pass is a simple key, not a path. Dots won't get special handling.

I think letting ptree have the dual container/path interface is the largest problem it has. I see so much confusion over it. Something to consider for the next version.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
  • Personally, I have never found a use case where Boost Property Tree was actually the right solution. For XML, use e.g. PugiXML (headeronly!). For JSON use any json parser, For INI file, use a trivial parser (I have 2 or so in SO answers :)). In my eyes, the functionality of Property Tree is basically crippled for any of these back ends, with little/no control over roundtrip fidelity. And it has the API quirks to boot. – sehe Dec 05 '14 at 11:07
  • The only things I'd say it has got going for it is (a) it's in boost (b) it has a single interface (though that is a very leaky abstraction!) (c) it has a wchar_t leg OotB. – sehe Dec 05 '14 at 11:08
  • Actually I think that you should not consider the property tree a parser for some configuration file but as a container. The fact that that container can be filled from different source formats is important but not fundamental. In my use case I use it as a versatile container for the configuration parameters of the concrete implementation of my interfaces – Triskeldeian Oct 14 '15 at 18:11