Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach Through QJsonObject to get Key/Value Pair

Tags:

c++

qt

I am wondering how I would foreach through a QJsonObject to get the key/value pairs in C++? So far, I am only able to get the value.

//main.cpp
QFile file(":/geoip.json");
file.open(QIODevice::ReadOnly);
QByteArray rawData = file.readAll();
file.close();
QJsonDocument doc(QJsonDocument::fromJson(rawData));
QJsonObject json = doc.object();
foreach(const QJsonValue &value, json) {
    QJsonObject obj = value.toObject();
    qDebug() << value;
}

//geoip.json
{
    "Afghanistan": "58.147.159.255",
    "Albania": "31.22.63.255",
    "Algeria": "105.235.143.255",
    "American Samoa": "202.70.115.241",
    "Andorra": "109.111.127.255",
    "Angola": "105.175.255.255",
    "Anguilla": "208.66.50.44",
    "Antarctica": "46.36.195.10"
}
like image 349
Jon Avatar asked Nov 28 '16 17:11

Jon


1 Answers

John already gave the answer. Using keys() a complete working solution would be:

#include <QCoreApplication>
#include <QFile>
#include <QByteArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //main.cpp
    QFile file("path/to/geoip.json");
    file.open(QIODevice::ReadOnly);
    QByteArray rawData = file.readAll();
    file.close();
    QJsonDocument doc(QJsonDocument::fromJson(rawData));
    QJsonObject json = doc.object();
    foreach(const QString& key, json.keys()) {
        QJsonValue value = json.value(key);
        qDebug() << "Key = " << key << ", Value = " << value.toString();
    }

    return a.exec();
}
like image 65
twisq Avatar answered Nov 08 '22 22:11

twisq