Erstellen von JSON-Arrays in Boost mithilfe von Eigenschaftsbäumen

Erstellen von JSON-Arrays in Boost mithilfe von Eigenschaftsbäumen


Ich versuche, ein JSON-Array mit Boost-Eigenschaftsbäumen zu erstellen.


In der Dokumentation heißt es:"JSON-Arrays werden Knoten zugeordnet. Jedes Element ist ein untergeordneter Knoten mit leerem Namen."


Ich möchte also einen Eigenschaftsbaum mit leeren Namen erstellen und dann write_json(...) aufrufen um das Array herauszuholen. Die Dokumentation sagt mir jedoch nicht, wie unbenannte untergeordnete Knoten erstellt werden. Ich habe ptree.add_child("", value) versucht , aber das ergibt:


Assertion `!p.empty() && "Empty path not allowed for put_child."' failed

Die Dokumentation scheint diesen Punkt nicht anzusprechen, zumindest nicht in irgendeiner Weise, die ich herausfinden kann. Kann jemand helfen?


Einige Code-Antworten


Assertion `!p.empty() &&
"Empty path not allowed for put_child."' failed
#include <boost/property_tree/ptree.hpp>
using boost::property_tree::ptree;
ptree pt;
ptree children;
ptree child1, child2, child3;
child1.put("", 1);
child2.put("", 2);
child3.put("", 3);
children.push_back(std::make_pair("", child1));
children.push_back(std::make_pair("", child2));
children.push_back(std::make_pair("", child3));
pt.add_child("MyArray", children);
write_json("test1.json", pt);
{
"MyArray":
[
"1",
"2",
"3"
] }
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);
{
"testkey": "testvalue",
"MyArray":
[
{ "childkeyA": "1", "childkeyB": "2"
},
{ "childkeyA": "3", "childkeyB": "4"
},
{ "childkeyA": "5", "childkeyB": "6"
}
] }
boost::property_tree::ptree root;
boost::property_tree::ptree child1;
boost::property_tree::ptree child2;
// .. fill in children here with what you want // ... ptree.push_back( std::make_pair("", child1 ) );
ptree.push_back( std::make_pair("", child2 ) );
else if (indent >
0 &&
pt.count(Str()) == pt.size())
using boost::property_tree::ptree;
ptree targetTree;
ptree arrayChild;
ptree arrayElement;
//add array elements as desired, loop, whatever, for example for(int i = 0;
i <
3;
i++) { arrayElement.put_value(i);
arrayChild.push_back(std::make_pair("",arrayElement)) }
targetTree.put_child(ptree::path_type("target.path.to.array"),arrayChild) 
#!/usr/bin/env python3   def lex_leaf(lf: str):
if lf.isdecimal():
return int(lf)
elif lf in ['True', 'true']:
return True
elif lf in ['False', 'false']:
return False
else:
try: return float(lf)
except ValueError: return lf def lex_tree(j):
tj = type(j)
if tj == dict:
for k, v in j.items(): j[k] = lex_tree(v)
elif tj == list:
j = [lex_tree(l) for l in j]
elif tj == str:
j = lex_leaf(j)
else:
j = lex_leaf(j)
return j def lex_file(fn: str):
import json
with open(fn, "r") as fp:
ji = json.load(fp)
jo = lex_tree(ji)
with open(fn, 'w') as fp:
json.dump(jo, fp) if __name__ == '__main__':
import sys
lex_file(sys.argv[1])
// Create JSON on the fly. json j2 = {   {"pi", 3.141},   {"happy", true},   {"name", "Niels"},   {"nothing", nullptr},   {"answer", {
{"everything", 42} }}, {"list", {1, 0, 2}}, {"object", {
{"currency", "USD"},
{"value", 42.99} }} };
// Or treat is as an STL container;
create an array using push_back json j;
j.push_back("foo");
j.push_back(1);
j.push_back(true);
// also use emplace_back j.emplace_back(1.78);
// iterate the array for (json::iterator it = j.begin();
it != j.end();
++it) { std::cout <<
*it <<
'\n';
}
 struct ptree
{
map<key_name,value>
data;
vector<pair<key_name,ptree>>
children;
};
// Write
bt::ptree root;
bt::ptree active;
bt::ptree requested;
bt::ptree n1, n2, n3;
n1.put("name", "Mark");
n1.put("age", 20);
n1.put("job", "aaa");
n2.put("name", "Rosie");
n2.put("age", "19");
n2.put("job", "bbb");
n3.put("name", "sunwoo");
n3.put("age", "10");
n3.put("job", "ccc");
active.push_back ({ "",l1 });
active.push_back ({ "",l2 });
requested.push_back({ "",l3 });
root.push_back
({"active", active});
root.push_back
({"requested", requested});
bt::write_json("E:\\1.json", root);
// READ
bt::ptree root2;
bt::ptree active2;
bt::ptree requested2;
bt::ptree r1, r2, r3;
bt::read_json("E:\\1.json", root2);
// loop children
for (auto&
[k,n] : root.get_child("active"))
{ cout <<
n.get<string>("name", "unknown");
cout <<
n.get<int>
("age"
, 11);
cout <<
n.get<string>("job"
, "man");
cout <<
endl <<
flush;
}