Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. how to get indented JSON values in C++ ?
Forum Update on Monday, May 27th 2025

how to get indented JSON values in C++ ?

Scheduled Pinned Locked Moved Solved General and Desktop
jsonc++json parserqt application
12 Posts 7 Posters 5.4k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Q Qjay
    3 Jun 2016, 07:58

    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

    Main.cpp

    #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;
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    
    
    
        // 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("http://en.wikitolearn.org/api.php?action=parse&page=Intro%20cryptography&format=json") ) );
           QNetworkReply *reply = mgr.get(req);
           eventLoop.exec();
    
           if (reply->error() == QNetworkReply::NoError) {
               //success
               //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 {
               //failure
               qDebug() << "Failure" <<reply->errorString();
               delete reply;
    
    
           }
    
            return app.exec();
    }
    
    
    

    This is the JSON that the API returns me

    QJsonObject({
    	"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"
    	}
    })
    
    P Offline
    P Offline
    Paul Colby
    wrote on 3 Jun 2016, 10:29 last edited by
    #2

    Hi @Qjay,

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

    Try:

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

    Cheers.

    1 Reply Last reply
    4
    • Q Offline
      Q Offline
      Qjay
      wrote on 3 Jun 2016, 10:55 last edited by
      #3

      Thanks paul colby !! It worked out .

      1 Reply Last reply
      0
      • Q Offline
        Q Offline
        Qjay
        wrote on 4 Jun 2016, 19:13 last edited by
        #4

        i also want to get pageid and revid too .

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

         jsonResponse.object()["parse"].toObject()["pageid"].toString();
        
        J 1 Reply Last reply 4 Jun 2016, 19:23
        0
        • Q Qjay
          4 Jun 2016, 19:13

          i also want to get pageid and revid too .

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

           jsonResponse.object()["parse"].toObject()["pageid"].toString();
          
          J Offline
          J Offline
          Joel Bodenmann
          wrote on 4 Jun 2016, 19:23 last edited by
          #5

          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():

          jsonResponse.object()["parse"].toObject()["pageid"].toInt();
          

          Industrial process automation software: https://simulton.com
          Embedded Graphics & GUI library: https://ugfx.io

          1 Reply Last reply
          0
          • A Offline
            A Offline
            Anil Patel
            wrote on 8 Aug 2018, 14:45 last edited by
            #6

            Hi All,

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

            M G 2 Replies Last reply 8 Aug 2018, 16:08
            0
            • A Anil Patel
              8 Aug 2018, 14:45

              Hi All,

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

              M Offline
              M Offline
              mrjj
              Lifetime Qt Champion
              wrote on 8 Aug 2018, 16:08 last edited by
              #7

              @Anil-Patel
              Hi
              Show how you "print" please ?

              A 1 Reply Last reply 9 Aug 2018, 07:30
              0
              • M mrjj
                8 Aug 2018, 16:08

                @Anil-Patel
                Hi
                Show how you "print" please ?

                A Offline
                A Offline
                Anil Patel
                wrote on 9 Aug 2018, 07:30 last edited by
                #8

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

                jsulmJ M 2 Replies Last reply 9 Aug 2018, 09:14
                0
                • A Anil Patel
                  9 Aug 2018, 07:30

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

                  jsulmJ Offline
                  jsulmJ Offline
                  jsulm
                  Lifetime Qt Champion
                  wrote on 9 Aug 2018, 09:14 last edited by
                  #9

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

                  https://forum.qt.io/topic/113070/qt-code-of-conduct

                  1 Reply Last reply
                  0
                  • A Anil Patel
                    9 Aug 2018, 07:30

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

                    M Offline
                    M Offline
                    mrjj
                    Lifetime Qt Champion
                    wrote on 9 Aug 2018, 09:17 last edited by mrjj 8 Sept 2018, 12:48
                    #10

                    @Anil-Patel
                    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.

                    1 Reply Last reply
                    0
                    • A Anil Patel
                      8 Aug 2018, 14:45

                      Hi All,

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

                      G Offline
                      G Offline
                      Gojir4
                      wrote on 9 Aug 2018, 11:37 last edited by
                      #11

                      @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.

                      A 1 Reply Last reply 9 Aug 2018, 12:24
                      2
                      • G Gojir4
                        9 Aug 2018, 11:37

                        @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.

                        A Offline
                        A Offline
                        Anil Patel
                        wrote on 9 Aug 2018, 12:24 last edited by
                        #12

                        @Gojir4
                        Sure, Thanks for your Help.

                        1 Reply Last reply
                        0

                        • Login

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • Users
                        • Groups
                        • Search
                        • Get Qt Extensions
                        • Unsolved