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

281 views Asked by At

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();
1

There are 1 answers

0
Parisa.H.R On

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"
}