How to get the first and the last of QJsonObject ?
-
Hi
is the QJsonObjects in a array ?
if yes, you can just parse the file and get the elements from the QJsonArray.
Unless they are in a array, there is really no concept of first and last. -
Use
begin()
for the first one and--end()
for the last one and then thekey()
/value()
methods of these iterators. Just make sure you don't go out of bounds (e.g. usingcount()
orsize()
). -
@Chris-Kawa
oh, you think he means first and last member of QJsonObject
and not the first and last QJsonObject in the doc ?
I read it as that :) -
I don't know, could be both ;) Lets see what the OP says he wants.
-
@Chris-Kawa said in How to get the first and the last of QJsonObject ?:
iterators.
I found iterator QJsonObject::begin() and iterator QJsonObject::end() can get them, but how to write the method completely
-
Let's say you have JSON like this:
{ "foo": { "value" : 42 }, "bar": { "value" : 53 }, "bazz": { "value" : 64 } }
Using iterators you can do this:
QJsonObject root = doc.object(); QJsonObject first_object = root.begin().value().toObject(); QJsonObject last_object = (--root.end()).value().toObject();
Keep in mind that, as @mrjj pointed out, objects in JSON format are unordered, meaning that it's not specified which object is first or last (the order of text doesn't matter), so
first_object
is most likely not gonna be the "foo" object. In particular Qt's implementation keeps the objects in a map, so you will likely get alphabetical order of keys. Don't rely on this though.If you want an ordered structure the only option in JSON are arrays, so you might want something like this:
[ { "foo": 42 }, { "bar": 53 }, { "bazz": 64 } ]
And then access to first and last elements would look something like:
QJsonArray root = doc.array(); QJsonObject first_object = root.at(0).toObject(); QJsonObject last_object = root.at(root.count() - 1).toObject();
You should of course add checks to verify that the root is an array, that it has any objects in it etc. I omitted those to make the point clear.