Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing in order to jsoncpp (c++)

Tags:

c++

json

jsoncpp

Consider the following example for which my source is

    Json::Value root;
    root["id"]=0;
            Json::Value text;
            text["first"]="i";
            text["second"]="love";
            text["third"]="you";
    root["text"]=text;
    root["type"]="test";
    root["begin"]=1;
    root["end"]=1;
    Json::StyledWriter writer;
    string strJson=writer.write(root);
    cout<<"JSON WriteTest" << endl << strJson <<endl;

I thought I'd write the json fields in the order of the lines. Instead the result is:

JSON WriteTest
{
   "begin" : 1,
   "end" : 1,
   "id" : 0,
   "text" : {
      "first" : "i",
      "second" : "love",
      "third" : "you"
   },
   "type" : "test"
}

I want json format is

JSON WriteTest
{
   "id" : 0,
   "text" : {
      "first" : "i",
      "second" : "love",
      "third" : "you"
   },
   "type" : "test"
   "begin" : 1,
   "end" : 1,
}

How can I write a Json order?

like image 890
user3853197 Avatar asked Mar 16 '23 17:03

user3853197


2 Answers

No, I don't think you can. JsonCpp keeps its values in a std::map<CZString, Value>, which is always sorted by the CZString comparison. So it doesn't know the original order you added items.

like image 177
The Dark Avatar answered Mar 18 '23 07:03

The Dark


This is my workaround to a get an ordered json output from jsoncpp

Json::Value root;
root["*1*id"]=0;
        Json::Value text;
        text["*1*first"]="i";
        text["*2*second"]="love";
        text["*3*third"]="you";
root["*2*text"]=text;
root["*3*type"]="test";
root["*4*begin"]=1;
root["*5*end"]=1;
Json::StyledWriter writer;
string resultString=writer.write(root);
resultString=ReplaceAll(resultString,"*1*", "");
resultString=ReplaceAll(resultString,"*2*", "");
resultString=ReplaceAll(resultString,"*3*", "");
resultString=ReplaceAll(resultString,"*4*", "");
resultString=ReplaceAll(resultString,"*5*", "");
cout<<"JSON WriteTest" << endl << resultString <<endl;

with RepleceAll function defined as this

std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
        size_t start_pos = 0;
        while((start_pos = str.find(from, start_pos)) != std::string::npos) {
            str.replace(start_pos, from.length(), to);
            start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
        }
        return str;
    }
like image 25
ansanes Avatar answered Mar 18 '23 05:03

ansanes