0

can any one suggest the solution, how I can create json of below format using boost json in C++

json required format is as below

{
      "myarray": 
        [
          [ 12, 12, 120, 120  ],
          [ 120, 12, 129, 120 ],
          [ 12, 120, 120, 129 ]
        ],

      "count": 3,
}

I tried using ptree put method, but it seems numbers are getting converted to string. Is it possible somehow using basic_tree or translator or something else in available in boost json library?

santosh
  • 1
  • 2
  • Looks like you might want to take a look at one of the answers here: https://stackoverflow.com/questions/2855741/why-does-boost-property-tree-write-json-save-everything-as-string-is-it-possibl Doesn't seem like boost really has proper JSON support. – Nathan Pierson Oct 08 '20 at 14:02
  • Boost got a json library a couple days ago: https://lists.boost.org/Archives/boost/2020/10/250129.php – user14717 Oct 08 '20 at 18:55

1 Answers1

0

As already mentioned by other user, boost ptree has some limitations.

If this is the only format you need, then you could code your own solution (tabs and newlines are only for readability):

using MyArray = vector<int>;
using MyArrays = vector<MyArray>;

string CreateJson(const MyArrays& v)
{
    ostringstream json;
    json << "{\n\t" << R"("myarray":[)" << "\n";

    for (const auto& vv : v)
    {
        json << "\t\t[";
        for (auto el : vv) json << el << ", ";
        json.seekp(-1, json.cur);
        json << "],\n";
    }
    json.seekp(-2, json.cur);
    json << "\n";

    json << "\t\t],\n\t" << R"("count":)" << v.size() << "\n}";
    return json.str();
}

Live Demo

With a little additional templating, you could adjust it for more types

StPiere
  • 4,113
  • 15
  • 24