
I just wanted to post a program I wrote that creates a boost::ptree, saves it to JSON, reads it back, then iterates through the tree and prints its nodes. #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <string> #include <iostream> using namespace std; using boost::property_tree::ptree; string indent(int level) { string s; for (int i=0; i<level; i++) s += " "; return s; } void printTree (ptree &pt, int level) { if (pt.empty()) { cerr << "\""<< pt.data()<< "\""; } else { if (level) cerr << endl; cerr << indent(level) << "{" << endl; for (ptree::iterator pos = pt.begin(); pos != pt.end();) { cerr << indent(level+1) << "\"" << pos->first << "\": "; printTree(pos->second, level + 1); ++pos; if (pos != pt.end()) { cerr << ","; } cerr << endl; } cerr << indent(level) << " }"; } return; } int main(int, char*[]) { // first, make a json file: string tagfile = "testing2.pt"; ptree pt1; pt1.put("object1.type","ASCII"); pt1.put("object2.type","INT64"); pt1.put("object3.type","DOUBLE"); pt1.put("object1.value","one"); pt1.put("object2.value","2"); pt1.put("object3.value","3.0"); pt1.put("object4.type", "ASCII"); pt1.put("object4.value", "shallow"); pt1.put("object4.subobject1.type", "ASCII"); pt1.put("object4.subobject1.value", "deep child"); pt1.put("object4.subobject1.subsubobject.type", "ASCII"); pt1.put("object4.subobject1.subsubobject.value", "deep child"); pt1.put("object5.type", "ASCII"); pt1.put("object5.value", "shallow"); write_json(tagfile, pt1); ptree pt; bool success = true; //try { read_json(tagfile, pt); printTree(pt, 0); cerr << endl; return success; } PROGRAM OUTPUT: rcook@rzbeast (blockbuster): ./ptree { "object1": { "type": "ASCII", "value": "one" }, "object2": { "type": "INT64", "value": "2" }, "object3": { "type": "DOUBLE", "value": "3.0" }, "object4": { "type": "ASCII", "value": "shallow", "subobject1": { "type": "ASCII", "value": "deep child", "subsubobject": { "type": "ASCII", "value": "deep child" } } }, "object5": { "type": "ASCII", "value": "shallow" } } -- ✐Richard Cook ✇ Lawrence Livermore National Laboratory Bldg-453 Rm-4024, Mail Stop L-557 7000 East Avenue, Livermore, CA, 94550, USA ☎ (office) (925) 423-9605 ☎ (fax) (925) 423-6961 --- Information Management & Graphics Grp., Services & Development Div., Integrated Computing & Communications Dept. (opinions expressed herein are mine and not those of LLNL)