0

I have a QString eg:

QString test = "Hello";
test += "\n";
test += "World";

I am saving this in a file :


QFile file("test.json");
if (!file.open(QIODevice::WriteOnly )) return;

jsonObj = QJsonObject()
jsonObj.insert("Key",test);

QJsonDocument doc;
doc.setObject(jsonObj);
file.write(doc.toJson());
file.close();

Now the output test.json file is:

{
"Key":"Hello\nWorld"
}

My desired output is:

{
"Key":"Hello
World"
}

The reason for doing it is because I am reading the same file again in another program ad there this \n is causing the error.

HARSH MITTAL
  • 750
  • 4
  • 17
  • [Related](https://stackoverflow.com/questions/42068/how-do-i-handle-newlines-in-json)? – alagner Sep 16 '22 at 10:05
  • @alagner I have tried that as well, but that seems to be working in javascript not in Qt C++ – HARSH MITTAL Sep 16 '22 at 10:50
  • 3
    Your desired json is not valid. So no you can't create this with Qt nor any other json writer. – chehrlic Sep 16 '22 at 12:14
  • 1
    my point was the same as @chehrlic's – alagner Sep 16 '22 at 13:47
  • Does this answer your question? [Are multi-line strings allowed in JSON?](https://stackoverflow.com/questions/2392766/are-multi-line-strings-allowed-in-json) – CharonX Sep 19 '22 at 13:10
  • Your desired output is not a valid JSON file. If you do not care about creating a valid JSON file you may consider e.g. [replacing](https://doc.qt.io/qt-5/qstring.html#replace) the escaped newline characters in `doc.toJson()` with non-escaped ones before writing them to a file, but I'd question the purpose of creating a JSON file in the first place. – CharonX Sep 19 '22 at 13:17
  • Thanks all, I'll try to have some alternate way of implementing it, I need JSON to be valid so I will probably go with a somewhat similar approach suggested by @CharonX – HARSH MITTAL Sep 19 '22 at 14:04
  • @HARSHMITTAL I need to re-iterate here, if your JSON file has linebreaks like in your example "desired", it is **NOT** a valid JSON file. You can manipulate the `QByteArray` output produced by `doc.toJson()`, but doing so **will** result in a broken JSON file (as - once again - linebreaks are not valid in JSON strings). – CharonX Sep 20 '22 at 07:32
  • I have the feeling that this may be a [X-Y Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - maybe taking another look as to **why** you want to have linebreaks in JSON strings will provide a better solution? – CharonX Sep 20 '22 at 07:39
  • So the only reason I wanted to have a line break is that in another application I wanted to read the data directly and since \n is added, the data was not parsed properly. Now I will be reading it as a std string rather than QString in my final application. – HARSH MITTAL Sep 20 '22 at 07:47

0 Answers0