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

Read JSON WITHOUT readAll()



  • Until now, I'm reading my JSON files using:

    QFile file(file_path);
    if(!file.open(QIODevice::ReadOnly)){
        qDebug() << "Failed to open " << file_path;
        exit(1);
    }
    
    QTextStream file_text(&file);
    QString json_string = file_text.readAll();
    file.close();
    
    QByteArray json_bytes = json_string.toLocal8Bit();
    
    auto json_doc = QJsonDocument::fromJson(json_bytes);
    
    if (json_doc.isNull()) {
        qDebug()<<"Failed to create JSON doc.";
        exit(2);
    }
    
    if (!json_doc.isObject()) {
        qDebug()<<"JSON is not an object.";
        exit(3);
    }
    
    QJsonObject json_obj = json_doc.object();
    
    if (json_obj.isEmpty()) {
        qDebug()<<"JSON object is empty.";
        exit(4);
    }
    
    // do some stuff
    

    It works great, but I would like to know if is possible to replace the readAll() method and read just a single JSON node/object/array from the JSON file.
    I was thinking about it because my JSON files are very big.

    Maybe, something like:

    QJsonObject my_node = file.magic_read().value("root").toObject().value("node_a").toObject();
    

    Is this possible?



  • doubtful...the json is a document format. so, to be parsed correctly it needs to be cached somewhere. The readall() pulls the whole document into memory so that it can be parsed.


Log in to reply