Project

General

Profile

How to add another Object into a Json object

Added by Jason D about 3 years ago

Hi, I'm new to C++ and trying to and add another Object into a Json object as below.
Line 5 doesn't compile and I've tried all ways I can think of or google. C++ is really much more complicated to work without some basic knowledge. Any help is greatly appreciated.

1: Wt::Json::Object request
2: Wt::Json::Value config(Wt::Json::Type::Object);
3: Wt::Json::Object &rConfig = config;
4: rConfig["encrypted"] = true;
5: request["config"] = Wt::Json::Value(config);

Trying to get following JSON
{
"config" : {
"encrypted": true,
...
},
...
}

Best Regards,
Jason


Replies (3)

RE: How to add another Object into a Json object - Added by Plug Gulp about 3 years ago

Hey Jason,

The Json object is inherited from std::map. So to initiate a Json object just use the C++ initializer list as follows:

Wt::Json::Object jobj{
    {"config", {
        {"encrypted", true},
        ...
    },
    ...
};

HTH,

~Plug

RE: How to add another Object into a Json object - Added by Plug Gulp about 3 years ago

I must also add that to insert a JSON object dynamically into another JSON object you can use the std::map::insert API as follows:

Wt::Json::Object jobj_a{
    {"key_a", true},
    {"key_b", 10}
};

Wt::Json::Object jobj_b{
    {"key_c", "val"},
    {"key_d", 'c'}
};

jobj_b.insert("key_e", jobj_a); // std::map::insert API
/*
after insert jobj_b will be:
{
    {"key_c", "val"},
    {"key_d", 'c'},
    {"key_e", {
        {"key_a", true},
        {"key_b", 10}
    }
}
*/

RE: How to add another Object into a Json object - Added by Jason D about 3 years ago

Thank you so much! That's super exciting to learn.

Best Regards,
Jason

    (1-3/3)