2

I'm trying to use boost json with property trees to decode a json message. I'm only interested about checking whether "mykey" is in the message and, if that is the case, get the corresponding values.
I'm a little lost in boost documentation, and I was trying to see what the actual code would be to parse a message such as the one below.

{ // some values "mykey": [ { "var1": "value1_str", "var2" : "value2" } ] // some other values } 

1 Answer 1

3

I don't know about Boost ptree for JSON. I've tried it but it seemed... very clunky.

Here's a simple JSON parser based on the RFC, made in Spirit: https://github.com/sehe/spirit-v2-json/tree/q21356666

You could use it for your use case like test.cpp

#include <vector> #include "json.hpp" struct X { static X from_json(JSON::Value const& v); std::string var1; double var2; }; int main() { auto doc = as_object(JSON::parse( "{\n" " // some values\n" " \"mykey\": [\n" " {\n" " \"var1\": \"value1_str\",\n" " \"var2\" : 3.14\n" " }\n" " ]\n" " // some other values\n" "}\n" )); if (doc.has_key("mykey")) { X data = X::from_json(doc["mykey"]); std::cout << "X.var1: " << data.var1 << "\n"; std::cout << "X.var2: " << data.var2 << "\n"; } std::cout << "doc: " << doc << "\n"; std::cout << "doc[\"mykey\"]: " << doc["mykey"] << "\n"; } X X::from_json(JSON::Value const& v) { X result; auto& o = as_object(as_array(v)[0]); result.var1 = as_string(o["var1"]); result.var2 = as_double(o["var2"]); return result; } 

Output:

X.var1: value1_str X.var2: 3.14 doc: {"mykey":[{"var1":"value1_str","var2":3.14}]} doc["mykey"]: [{"var1":"value1_str","var2":3.14}] 

There are other json libraries around. I suggest you select one to suit your needs.

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

5 Comments

Thanks a lot for your answer. Very instructive. For now, I'd prefer to wait and see if someone can help with ptree and boost json. I'd prefer to not change too much in the code.
as a side note, is the '\n' at the end of 'doc' necessary? and why are you using 'auto'?
@Bob It's JSON, of course it's not required. And I'm lazy. Feel free to type JSON::Object
could you also provide an example about generating the json, as opposed to type in the values? Thank you..
Added two lines at the end that show how to serialize to JSON. See also the other samples in the master branch

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.