-1

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();
mahya
  • 51
  • 4
  • your code is completely wrong , because you are writing in JSON file but do this like a text file . – Parisa.H.R Jun 24 '21 at 20:35
  • If you want to use JSON you should follow the rules of it . I don't know why you don't want to use the (key, value) format in your .json file. See this [JSON](https://en.wikipedia.org/wiki/JSON) – Parisa.H.R Jun 24 '21 at 20:53
  • As I know this is wrong , but you mean this `QFile file("tmp.json");` `if(!file.open(QFile::WriteOnly | QFile::Text))` `return;` `QTextStream in(&file);` `in << "how are you do" ;` `file.flush();` `file.close();` means that save one text that usually saves in .txt file in .json file .????? – Parisa.H.R Jun 24 '21 at 21:10
  • I do not have special keys but a bunch of string-list. Is it wrong to use only values there? – mahya Jun 25 '21 at 13:31
  • why you don't save them in .txt file? – Parisa.H.R Jun 25 '21 at 13:39

1 Answers1

0

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"
}
Parisa.H.R
  • 3,303
  • 3
  • 19
  • 38