Need example for reading/writing json files

  • Hello everybody!

    Qt has excellent documentation. Sometimes elaborate examples can save us time.
    i am following this link to understand how to read/parse json from a website. This code works for some websites but not for some ( can someone explain why this might be happening?). Plus how to convert Json object to array or rather how do you parse data in Qt for Json files?

        QUrl url = QString::fromLocal8Bit("");
        QNetworkRequest request(url);
        delete ui;
    void Dialog::onFinished(QNetworkReply* response)
        QVariant redirectionTarget = response->attribute(QNetworkRequest::RedirectionTargetAttribute);
        qDebug() << redirectionTarget;
        if (!redirectionTarget.isNull()) {
                QUrl newUrl = QUrl(redirectionTarget.toUrl());
                QNetworkRequest request(newUrl);
        } else {
            byteResponse = (QByteArray)response->readAll();       
           jsonResponse = QJsonDocument::fromJson(byteResponse);
               jsonObject = jsonResponse.object();
               qDebug() <<"document is an object";
    /* HOW DO YOU CONVERT jSon Object to Json array and ??????*/
                jsonArray = jsonResponse.array();
                qDebug() <<"document is an Array";
                foreach(const QJsonValue &value, jsonArray)
                    QJsonObject obj = value.toObject();

  • @Muzab

    This code works for some websites but not for some

    Could you be more specific about details? Some URLs for sites not working?
    I tried the URL from you code sample ("") and I got a 404 error, no JSON file at all so at that point Qt is out of the equation.

    In addition, I'd sepatate the JSON processing from the network connections, so could you try processing a JSON file (gathered from some of the sites "not working", I mean, I'd connect and save the JSON data by hand into a file and then I'd feed it to the JSON object)

    Also, have you played with this example?

  • Hi Pablo I have updated the weblink that I want to read data from but I cannot read the contents of the array to a QByteArray. But I can for this link "".
    It is on the same server.
    Thanks for pointing out the example. I will test it out.

  • Sorry guys! My code works, just website was wrong

  • @Muzab I'm glad you solved your problem. I was about to suggest this website JSONLint an online JSON validation tool. I use it frequently to be sure the JSON data I'm handling is valid, so the parsing code I write should be as well.

    Please don't forget to mark this post as solved. Thanks.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.