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

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


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


If you use Qt 4, you can use QJson lib.

In this case the usage will be as following:

QJson::Parser parser;bool ok;QVariantMap result = parser.parse (responseData, &ok).toMap();if (!ok) {  qFatal("An error occurred during parsing");  exit (1);}