Dut
Dut

Reputation: 39

Parse unnamed JSON Array from a web service in Qt

I am trying to parse this JSON from a web service.

  [
      {
        "word": "track",
        "score": 4144
      },
      {
        "word": "trail",
        "score": 2378
      },
      {
        "word": "domestic dog",
        "score": 51
      },
      {
        "word": "dogiron"
      }
  ]

When I log out the response from the API call as a QString as below, it comes out fine but with all quotes escaped, thus not making it a valid JSON:

QString response = (QString) data->readAll();
qDebug() << "Return data: \n" << response;

Examples I have seen so far (e.g. Parse jsonarray?) only parse named arrays which they grab from a QJsonObject by name. Any hints on how to use QJsonArray directly or together with QJsonDocument::fromJson() on the return data?

Upvotes: 1

Views: 2287

Answers (1)

Daniel Waechter
Daniel Waechter

Reputation: 2773

QJsonDocument has a member called array() that returns the QJsonArray contained in the document.

For example:

QFile file("main.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
QByteArray jsonData = file.readAll();
file.close();

QJsonParseError parseError;
QJsonDocument document = QJsonDocument::fromJson(jsonData, &parseError);

if (parseError.error != QJsonParseError::NoError)
{
    qDebug() << "Parse error: " << parseError.errorString();
    return;
}

if (!document.isArray())
{
    qDebug() << "Document does not contain array";
    return;
}

QJsonArray array = document.array();

foreach (const QJsonValue & v, array)
{
    QJsonObject obj = v.toObject();
    qDebug() << obj.value("word").toString();
    QJsonValue score = obj.value("score");
    if (!score.isUndefined())
        qDebug() << score.toInt();
}

Upvotes: 7

Related Questions