Search code examples
jsonqtformattingstring-formatting

How to format a JSON string to a readable output in QT


I have a JSON string

{
"FirstName": "John",
"LastName": "Doe",
"Age": 43,
"Address": {
    "Street": "Downing Street 10",
    "City": "London",
    "Country": "Great Britain"
},
"Phone numbers": [
    "+44 1234567",
    "+44 2345678"
]
}

in QString variable. I found (somewhere here in Stackoverflow) a way to format XML:

QString responseData = "";
responseData = networkResponse->readAll();

QString formattedXMLResponse;
QDomDocument input;
input.setContent(responseData);
QDomDocument output(input);
QTextStream stream(&formattedXMLResponse);
output.save(stream, 2);

ui->outputTB->setPlainText(formattedXMLResponse);

But this code works fine just for XML. Any thoughts how JSON can be formatted?


Solution

  • QJsonDocument takes a format to its toJson function, allowing you to specify either a compact or indented format.

    Assuming you have your JSON in a QJsonObject called jsonObj:

    QJsonDocument doc(jsonObj);
    QString jsonString = doc.toJson(QJsonDocument::Indented);
    

    Or, from a QString:

    QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
    QString formattedJsonString = doc.toJson(QJsonDocument::Indented);