[Interest] iterate through JSON data

Larry Martell larry.martell at gmail.com
Tue May 17 04:02:07 CEST 2016


On Mon, May 16, 2016 at 7:53 PM, Hamish Moffatt
<hamish at risingsoftware.com> wrote:
> On 17/05/16 08:24, Larry Martell wrote:
>>
>> I've see a lot of code that does something like this:
>>
>>      QJsonDocument document = QJsonDocument::fromJson(jsonData);
>>      QJsonObject object = document.object();
>>      QJsonValue value = object.value("capData");
>>
>> But I don't want to hard code the keys - I want to pick up and store
>> whatever happens to be in the JSON file. How can I iterate through it
>> and do that?
>>
>> Also, what would be the best object to store this in so I can later
>> access it as I want to?
>>
>
> QJsonObject has iterator methods, and for each value you can check if it is
> itself an array or an object or a simple type (QJsonValue::isArray(),
> isObject(), isString() etc).
>
> As for another object, I can't think of another with this flexibility. Why
> not leave it in the QJson* objects?

My JSON file looks like this:


{
   "capData": {
      "host": "foo.bar.com",
      "initial_port": "8000"
      "secondary_port": "8001"
   },
   "django": {
      "host": "baz.bar.com",
      "port": "8004"
   }
}


My code looks like this:


  QFile file(QCoreApplication::applicationDirPath() + "/" + CONFIG_PATH);
  QByteArray val;
  QJsonDocument config_json;
  QJsonObject config;

  if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    val = file.readAll();
    file.close();
    config_json = QJsonDocument::fromJson(val);
    config = config_json.object();
    QJsonValue value = config.value("capData");
    QJsonArray array = value.toArray();
    foreach (const QJsonValue & v, array)
        qWarning() << v.toObject().value("host").toString();
  }

I never enter my foreach loop, so I wrote out each variable with qWarning().

When I print out val it has:

"{\n   \"capData\": {\n      \"host\": \"foo.bar.com\",\n
\"initial_port\": \"8000\"\n      \"secondary_port\": \"8001\"\n
},\n   \"django\": {\n      \"host\": \"baz.bar.com\",\n
\"port\": \"8004\"\n   }\n}\n"

But when I print out config_json I get:

QJsonDocument()

When I print out config I get:

QJsonObject()

When I print out value I get:

QJsonValue(undefined)

When I print out array I get:

QJsonArray()

I am probably doing something very simple and very stupid wrong, but I
don't know what it is.



More information about the Interest mailing list