Tuesday, April 24, 2018

how to get cpp boost ptree json array root json string

Why
because default cpp boost ptree json not support root array json format.
there is so many other json parse engine on internet.
buy i want to reused boost ptree.

my code:
ptree r, r0, p1, p2;
ptree p0, p, c1, c2;

c1.put("c1a", "a");
c1.put("c1b", "b");
c2.put("c2a", "a");
c2.put("c2b", "b");

p.push_back(std::make_pair("", c1));
p.push_back(std::make_pair("", c2));
p0.push_back(std::make_pair("", p));
std::string s;
std::stringstream ss;
write_json(ss, p0);
s = ss.str();



i want to get below string format:
[
   {...},
   {...}
  ]


but boost ptree generate string like this:
{
  "":[
   {...},
   {...}
  ]
}

How:
remove string above of '[' and after ']':
std::string getJArrayString(const ptree& p) {
ptree p0;
p0.push_back(std::make_pair("", p));

std::stringstream ss;
write_json(ss, p0);
std::string s = ss.str();

do {
auto b = s.find_first_of('[');
if (b == std::string::npos)
break;

auto e = s.find_last_of(']');
if (e == std::string::npos)
break;
s = s.substr(b, e + 1 - b);

return s;
} while (false);

return "[]";

}

and call this:

ptree r, r0, p1, p2;
ptree p0, p, c1, c2;

c1.put("c1a", "a");
c1.put("c1b", "b");
c2.put("c2a", "a");
c2.put("c2b", "b");

p.push_back(std::make_pair("", c1));
p.push_back(std::make_pair("", c2));
p0.push_back(std::make_pair("", p));
std::string s = getJArrayString(p0);

No comments: