how to get indented JSON values in C++ ?

  • Hey guys i know how to get indented JSON values in QML/JS .

    But how to get it in C++

    i want to get text section from it : text seciton contains HTML . Later i want to store this html in a html file
    Please just go through my code and see the result


    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QDebug>
    #include <QNetworkAccessManager>
    #include <QNetworkRequest>
    #include <QNetworkReply>
    #include <QUrl>
    #include <QUrlQuery>
    #include <QJsonObject>
    #include <QJsonDocument>
    #include <QByteArray>
    #include <QFile>
    int main(int argc, char *argv[])
        QGuiApplication app(argc, argv);
        QQmlApplicationEngine engine;
        // create custom temporary event loop on stack
           QEventLoop eventLoop;
           // "quit()" the event-loop, when the network request "finished()"
           QNetworkAccessManager mgr;
           QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
           // the HTTP request
           QNetworkRequest req( QUrl( QString("") ) );
           QNetworkReply *reply = mgr.get(req);
           if (reply->error() == QNetworkReply::NoError) {
               //qDebug() << "Success" <<reply->readAll();
              QString   html = (QString)reply->readAll();
              QJsonDocument jsonResponse = QJsonDocument::fromJson(html.toUtf8());
              QJsonObject jsonObj = jsonResponse.object();
            qDebug() <<  jsonObj;
            qDebug() << "parse" << jsonObj["parse"].toString();
               //  qDebug() << html;
               delete reply;
           else {
               qDebug() << "Failure" <<reply->errorString();
               delete reply;
            return app.exec();

    This is the JSON that the API returns me

    	"parse": {
    		"categories": [{
    			"*": "Cryptography",
    			"missing": "",
    			"sortkey": ""
    		"displaytitle": "Intro cryptography",
    		"externallinks": [],
    		"images": [],
    		"iwlinks": [],
    		"langlinks": [],
    		"links": [],
    		"pageid": 510,
    		"properties": [],
    		"revid": 2513,
    		"sections": [],
    		"templates": [],
    		"text": {
    			"*": "<p>Introduction to Cryptography  \n</p><p><b>What is Cryptography&#160;?</b>\nCryptography is a method of storing and transmitting data in a particular form so that only those for whom it is intended can read and process it\n</p><p><b>Cryptography is everywhere</b>\n</p><p>- Web traffic&#160;: HTTPS \n- wireless Traffic&#160;: 802.11&#160;; WPA2 , GSM , Bluetooth \n</p><p>- content protection&#160;: DVD , blu-ray (CSS&#160;: content scramble system )\n</p><p>- User authentication\n</p>\n<pre>    Secure communication&#160;: cryptography makes it possible for Alice and bob to communicate securely . \n</pre>\n<p>||ALICE|| -----------HTTPS/TLS-----------&gt;||BOB||\n</p><p>User authentication has 2 main parts&#160;:\n</p><p>1. Handshake protocol&#160;: establishes shared secret key using public-key cryptography \n2. Record layer&#160;: Transmit data using shared secret key . Ensure confidantiality and integrity .\n</p><p><br />\n<b>Building block&#160;: Symmetric Encryption</b>\n</p>\n<pre> Symmetric encryption is the oldest and best-known technique. A secret key, which can be a number, a word, or just a string of random letters, is applied to the text of a message to change the content in a particular way. \n</pre>\n<pre>E&#160;: encryption , D: decryption , PT&#160;: plaintext  , CT: ciphertext\n</pre>\n<p>E(PT) = CT \nD(E(PT)) = PT \n</p><p><b>USE CASES</b>\n</p>\n<pre>Single use key &#160;: key is only used to encrypt one message\nencrypted e-mail&#160;: new key generated for every mail . \n</pre>\n<pre>Multi use key&#160;: (many time key )\n Key used to encrypt multiple messages . \nencrypted files &#160;: same key used for many files . \n</pre>\n<p>Things to remember  \n</p><p>- Cryptography is &#160;: \n</p>\n<pre>                    * a tremendous tool \n                    * the basis for many security mechanisms\n</pre>\n<p>- Cryptography is not&#160;:\n</p>\n<pre>                    * a solution to all security problems \n                    * reliable unless implemented or used properly\n                    * something you should try to invent yourself .\n</pre>\n<!-- \nNewPP limit report\nCached time: 20160603075003\nCache expiry: 86400\nDynamic content: false\nCPU time usage: 0.008 seconds\nReal time usage: 0.009 seconds\nPreprocessor visited node count: 1/1000000\nPreprocessor generated node count: 4/1000000\nPost‐expand include size: 0/2097152 bytes\nTemplate argument size: 0/2097152 bytes\nHighest expansion depth: 1/40\nExpensive parser function count: 0/100\n-->\n\n<!-- \nTransclusion expansion time report (%,ms,calls,template)\n100.00%    0.000      1 - -total\n-->\n\n<!-- Saved in parser cache with key enwikitolearn:pcache:idhash:510-0!*!*!*!*!*!* and timestamp 20160603075003 and revision id 2513\n -->\n"
    		"title": "Intro cryptography"

  • Hi @Qjay,

    i want to get text section from it : text seciton contains HTML


    qDebug() << jsonResponse.object()["parse"].toObject()["text"].toObject()["*"].toString();


  • Thanks paul colby !! It worked out .

  • i also want to get pageid and revid too .

    I tried this : but was not able to get the pageid :/


  • The pageid value in your JSON is not a string but rather an integer, hence you have to use QJsonValue::toInt() instead of QJsonValue::toString():


  • Hi All,

    Need some help from you,
    How to remove "\n" between Two Json Attribute while printing .

  • Lifetime Qt Champion

    Show how you "print" please ?

  • @mrjj {
    "app": "PromotionDngineyscad",
    "host": "WINASBAV7d7d750142-UBN",
    "log": "PromoLog",
    "lvl": "Messages",
    "msg": "Initialized",
    "thread": "237fbb2db10",
    "timestamp": "1533796312.526572",
    "uuid": "e62191c4-8891-4c92-a908-da01a3dakje3ac7ad"

  • Lifetime Qt Champion

    @Anil-Patel You should reread the question from @mrjj

  • Lifetime Qt Champion

    I did mean the code :)
    if you use printf, qDebug, or what ever.

    You could use QString's replace if the newline are truely in the the json string.

  • @Anil-Patel Hi,
    Please make a new post for a new question, even more if you are not the author of the original question...

    For your issue, I think you need to call QJsonDocument::toJson(QJsonDocument::Compact) when you export your json content to string.

  • @Gojir4
    Sure, Thanks for your Help.