[Interest] iterate through JSON data

Alexey Rusakov ktirf at users.sf.net
Tue May 17 05:18:39 CEST 2016


On 17 May 2016 at 12:01, Larry Martell <larry.martell at gmail.com> wrote:

> >> 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()
> >
> >
> > Your JSON is invalid - you're missing a comma on the end of the initial_port
> > line. config_json.isEmpty() is true as a result, and isObject() is false.
>
> Argh! Thank you so much for noticing that. Also, someone emailed me
> off list and pointed out that I should not use toArray() but
> toObject(). So now I have:
>
>     QJsonObject obj = config.value("capData").toObject();
>     foreach (const QJsonValue & v, obj)
>         qWarning() << v.toObject().value("host").toString();
>
> When I print out obj I have:
>
> QJsonObject({"host":"foo.bar.com","initial_port":"8000","secondary_port":"8001"})
>
> But in the foreach loop v.toObject().value("host").toString() is an
> empty string.
That was me - sorry for an off-list message. Now you're over-casting
your value to an Object whereas you shouldn't. This part brings you
nowhere:
> v.toObject().value("host")
while your values are actually here:
> qWarning() << v.toString();

And just for your interest, you might even want to do
> qWarning() << v;

This won't give you key names, though. I use a STL-style iterators to
get the whole pack:
> for (auto iter = obj.begin(); iter != obj.end(); ++iter)
>     qWarning() << iter.key() << "->" << iter.value();

-- 
  Alexey Rusakov



More information about the Interest mailing list