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. Read JSON WITHOUT readAll()
Qt 6.11 is out! See what's new in the release blog

Read JSON WITHOUT readAll()

Scheduled Pinned Locked Moved Solved General and Desktop
2 Posts 2 Posters 729 Views 1 Watching
  • 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.
  • F Offline
    F Offline
    fem_dev
    wrote on last edited by
    #1

    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?

    1 Reply Last reply
    0
    • Kent-DorfmanK Offline
      Kent-DorfmanK Offline
      Kent-Dorfman
      wrote on last edited by
      #2

      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.

      The dystopian literature that served as a warning in my youth has become an instruction manual in my elder years.

      1 Reply Last reply
      4

      • Login

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