简体   繁体   中英

How to write a sentence into JSON file in Qt not necessarily in JSON format?

I want to write a sentence into a JSON file in Qt. I did it in python and it was quite easy, no need to convert the text into (value, key) pairs but in Qt what I search is only in this format. I wrote a piece of code that splits the sentence into strings and tries to convert the list of strings into the JSON array and then write it into a json file. The problem is that it compiles without error and makes a tmp.json file with a size of 1Kb but with no content inside.

    QFile f("PATH/tmp.json");
    QString str = "how are you do";
    f.open(QIODevice::ReadWrite);
    QJsonArray disk_array = QJsonArray::fromStringList(str.split(' '));
    QJsonDocument jsonDoc;
    jsonDoc.setArray(disk_array);
    f.write(jsonDoc.toJson());
    f.close();

This code do this :

 QFile  dat("tmp.json");

 dat.resize(0);

 QString str = "how are you do";
 QJsonDocument  doc;
 QJsonObject    obj;

 obj["tempText"] = str;

 doc.setObject(obj);
 QByteArray  data_json = doc.toJson();

 if (dat.open(QIODevice::WriteOnly | QIODevice::Text))
 {
    dat.write(data_json);
    dat.flush();
    dat.close();
 }

and the output is like this in tmp.json file :

{
"tempText": "how are you do"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM