1

According to this, A JSON starting with bracket is valid, so i have encoded a list of item, in a test.json file:

[{"name": "a"},{"name": "b"}]

Heavily inspirated by this answer, i push this code in main.cpp:

#include <QApplication>
#include <QFile>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QVariant>
#include <QDebug>
#include <iostream>


int main(int argc, char *argv[]) {
      // Reading the JSON, parse it, get data as QJsonObject
      QString val;
      QFile file;
      file.setFileName("test.json");
      file.open(QIODevice::ReadOnly | QIODevice::Text);
      val = file.readAll();
      file.close();
      QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
      QJsonObject sett2 = d.object();

      // Printings
      qWarning() << "File content: " << val;
      qWarning() << "sett2: " << sett2 << " (empty: " << sett2.empty() << ')';

      // try to access the data directly
      QJsonValue value = sett2.value(QString("name"));
      qWarning() << "name value: " << value;
      QJsonObject item = value.toObject();
      qWarning() << "QJsonObject of accessed value: " << item;
}

Here is the output:

File content: "[{\"name\": \"a\"},{\"name\": \"b\"}]\n"
sett2:  QJsonObject()  (empty:  true )
name value: QJsonValue(undefined)
QJsonObject of accessed value:  QJsonObject()

We see that the file is properly readed. However, no data seems to be accessed : sett2 is empty, as if holding no data.

After searching on the QJsonObject documentation, i can't found any routine that can give access to the data in the file, in this case: the only one that seems to allow an access to fields is the value(), method, but it needs a parameter. Call it with 0, 1, NULL "name", "a", "b" and "knock knock" lead to compilation error or empty data. Other methods, like keys(), returns also empty data.

How access data of objects ? (here, name: "a" and name: "b")

Community
  • 1
  • 1
aluriak
  • 5,559
  • 2
  • 26
  • 39

1 Answers1

4

The answere is simple - you have to call QJsonDocument::array() instead of object:

QJsonArray sett2 = d.array();
Felix
  • 6,885
  • 1
  • 29
  • 54