Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 223
Andrii Muzychuk Avatar asked Sep 22 '14 15:09

Andrii Muzychuk


People also ask

What is JSON output format?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

Does Qt support JSON?

Qt provides support for dealing with JSON data. JSON is a format to encode object data derived from Javascript, but now widely used as a data exchange format on the internet. The JSON support in Qt provides an easy to use C++ API to parse, modify and save JSON data.


2 Answers

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);
like image 109
TheDarkKnight Avatar answered Oct 07 '22 01:10

TheDarkKnight


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);
}
like image 33
Max Go Avatar answered Oct 07 '22 00:10

Max Go