Create json array using boost property_tree
I am having problems creating a json array using boost library, a property tree in C ++.
I used this link , especially this part
ptree pt;
ptree children;
ptree child1, child2, child3;
child1.put("childkeyA", 1);
child1.put("childkeyB", 2);
child2.put("childkeyA", 3);
child2.put("childkeyB", 4);
child3.put("childkeyA", 5);
child3.put("childkeyB", 6);
children.push_back(std::make_pair("", child1));
children.push_back(std::make_pair("", child2));
children.push_back(std::make_pair("", child3));
pt.put("testkey", "testvalue");
pt.add_child("MyArray", children);
write_json("test2.json", pt);
leads to:
{
"testkey": "testvalue",
"MyArray":
[
{
"childkeyA": "1",
"childkeyB": "2"
},
{
"childkeyA": "3",
"childkeyB": "4"
},
{
"childkeyA": "5",
"childkeyB": "6"
}
]
}
But what should I do if I want to achieve a simple array without any object containing it? Like this:
[
{
"childkeyA": "1",
"childkeyB": "2"
},
{
"childkeyA": "3",
"childkeyB": "4"
},
{
"childkeyA": "5",
"childkeyB": "6"
}
]
Thank you very much.
+3
source to share
2 answers
Finally, I have not found a solution using the boost library. But this can be achieved with cpprestsdk ("Casablanca").
Example:
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace web::json;
void testFunction(http_request req)
{
// only to test the serialization of json arrays
json::value elmnt1;
elmnt1[L"element"] = json::value::string(U("value1"));
json::value elmnt2;
elmnt2[L"element"] = json::value::string(U("value2"));
json::value response; // the json array
response[0] = elmnt1;
response[1] = elmnt2;
string outputStr = utility::conversions::to_utf8string(shifts.serialize());
req.reply(200, outputStr, "application/json");
};
And this leads to
[
{
"element":"value1"
},
{
"element":"value2"
}
]
+1
source to share
The Boost documentation for JSON support is just a few lines:
The property tree dataset is not injected and does not support arrays as such . So the following JSON / property tree mapping is used:
- JSON objects are mapped to nodes. Each property is a child node.
- JSON arrays are mapped to nodes. Each element is a child node with an empty name. If a node has named and unnamed child nodes, it cannot be matched against the JSON representation.
- JSON values ββare mapped to nodes containing this value. However, all types of information are lost; numbers as well as literals "null", "true" and "false" are simply matched against their string form.
- Properties tree nodes containing both child nodes and data cannot be displayed.
JSON round-trip, except for loss of type information.
Underline mine
+2
source to share