Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QJsonObject not working right? cannot debug?



  • I'm trying to load a json file, and apply the data to my QJsonArray. But I first need to use a QJsonObject and use that to get my array. I'm not having much luck debugging the QJsonObject always shows it has 6 items that are inaccessible, but log to console fine... But then don't output into the array...
    Any ideas why this is not working?
    My code bellow:

        QFile file(":/stations.json");
        file.open(QIODevice::ReadOnly | QIODevice::Text);
        QByteArray file_data = file.readAll();
        file.close();
    
        QJsonParseError JsonParseError;
        QJsonDocument doc = QJsonDocument::fromJson(file_data, &JsonParseError);
        QJsonObject obj = doc.object();
        QJsonArray stations = obj["stations"].toArray();
    
        // debug
        QString jsonString = doc.toJson(QJsonDocument::Indented);
        QString strFromObj = QJsonDocument(obj).toJson(QJsonDocument::Compact).toStdString().c_str();
        qDebug() << strFromObj;
    

    And a sample json:

    {
        "stations" : [
            ["94648", "IDS60801", "SA", "Adelaide (West Terrace /  ngayirdapira)", "-34.9", "138.6"],
            ["94675", "IDS60801", "SA", "Adelaide (Kent Town)", "-34.9", "138.6"]
        ]
    }
    


  • looks like it is actually working! It just not possible to debug this except through qDebug messages.


  • Moderators

    Your code doesn't do anything with JsonParseError or stations. Your debug code doesn't do anything with jsonString.

    What do you get when you call this?:

    qDebug() << JsonParseError.errorString();
    qDebug() << stations;
    


  • looks like it is actually working! It just not possible to debug this except through qDebug messages.


  • Moderators

    @Gibbz said in QJsonObject not working right? cannot debug?:

    It just not possible to debug this except through qDebug messages.

    You can debug it however you want. I prefer qDebug() because its interface is a lot nicer; you can pass a QJsonDocument or QJsonObject or QJsonArray straight in:

    QJsonDocument doc = QJsonDocument::fromJson(file_data, &JsonParseError);
    QJsonObject obj = doc.object();
    QJsonArray stations = obj["stations"].toArray();
    
    qDebug() << doc;
    qDebug() << obj;
    qDebug() << stations;
    
    QString strFromObj = QJsonDocument(obj).toJson(QJsonDocument::Compact).toStdString().c_str();
    qDebug() << strFromObj;
    

    It doesn't make sense to convert everything to a C String and then back to a QString.

    You can implicitly convert a QByteArray directly to a QString...

    QString strFromObj = QJsonDocument(obj).toJson(QJsonDocument::Compact);
    

    ...or you can debug using std::string and std::cout:
    ``
    std::cout << QJsonDocument(obj).toJson(QJsonDocument::Compact).toStdString();


Log in to reply