0

I am using boost::property_tree::ptree to add data and create JSON file. The following is the recursive code that I have written -

using Strings = vector<string>;
Strings _headers;
map<string, Strings>        _subHeaders;
namespace pt = boost::property_tree;

void flushHeader(pt::ptree& headersNode, const Strings& headers) const {
    for(auto& header : headers) {
        pt::ptree headerNode;
        pt::ptree subHeaderNode;
        pt::ptree subHeaderObjNode;
        headerNode.put(header, "");
        if(_subHeaders.find(header) != _subHeaders.end()) {
            flushHeader(subHeaderObjNode, _subHeaders.find(header)->second);
            subHeaderNode.push_back(make_pair("", subHeaderObjNode));
            headerNode.put_child(pt::ptree::path_type(header, '|'), subHeaderNode);
        }
        headersNode.push_back(make_pair("", headerNode));
    }   
}


void flushData(pt::ptree& parent) const {
pt::ptree headersNode;
flushHeader(headersNode, _headers);
parent.put_child("Headers", headersNode);
}

JSON file created using the above code is something like this -

                   "Headers": [
                        {
                            "A": ""
                        },
                        {
                            "B": [
                                [
                                    {
                                        "X": ""
                                    },
                                    {
                                        "Y": ""
                                    }
                                ]
                            ]
                        }
                    ]

There are two brackets - [ after the value B whereas ideally only one [ should be present. So I want my JSON to look like this -

                       "Headers": [
                            {
                                "A": ""
                            },
                            {
                                "B": [
                                        {
                                            "X": ""
                                        },
                                        {
                                            "Y": ""
                                        }
                                ]
                            }
                        ]

I hope I have explained the problem clearly. What changes can I make in my code to get the desired JSON file? Thanks.

Harshu
  • 91
  • 9
  • Please provide a [mre]. Property tree is not able to produce all JSON documents, I'd recommend using a dedicated JSON library – Alan Birtles Mar 17 '20 at 07:43
  • Why don't you just use `boost`'s json parser? – ALX23z Mar 17 '20 at 07:49
  • @ALX23z Actually I am making these changes in an existing codebase that is using property tree to create the JSON file. I am adding new data in the same JSON file – Harshu Mar 17 '20 at 07:52

0 Answers0