How to iterate arrays in 2.0 and get the key

Apr 1, 2014 at 4:42 PM
In 1.4 I could look at iter->first to get the key and iter->second to get the value but I cant figure out how to get the key for an iterator to figure out which value it is.
Coordinator
Apr 1, 2014 at 5:12 PM
Hi Ryland42,

One of the major changes we've made in Casablanca 2.0 is to change the underlying storage for arrays to use a standard STL vector. The iterators returned from begin() and end() are into this underlying vector (and therefore satisfy the RandomAccessIterator C++ concept: RandomAccessIterator).

To more concretely answer your question: You can subtract the begin() iterator from your current iterator to get the offset (effectively the key).

roschuma
Apr 1, 2014 at 5:14 PM
I need to find the text key (foo below):

"foo":42

for the iterator values. It does look like "as_object()" would give me an iterator of <String, web::value>.
Coordinator
Apr 1, 2014 at 5:23 PM
Hi again,

Ok, so if you have a JSON document like
{
    "foo" : 42,
    "bar" : 97
}
then you're dealing with a JSON object. To manipulate a JSON object, you should use the as_object() method on a json::value to get an object, then use begin() and end() to get iterators for the object. These iterators should allow you to use iter->first to access the key as a utility::string_t.

If you have a document like
[ 42, 97 ]
then you're dealing with a JSON array. To manipulate an array, you should use the as_array() method and do what I described above.

roschuma
Apr 1, 2014 at 5:26 PM
The document looks like this:

{"gameInfo": [
{ "id":1,
"name":"foobar"
},
{ "id":2,
"name":"barfood"
}
]
}

I need to be able to see that the item Im iterating over has a key of "id" and another one with a key of "name".
Coordinator
Apr 1, 2014 at 5:35 PM
So for a document like you proposed (which has an array of objects):
{
    "gameInfo" : [
        {
            "id" : 1,
            "name" : "foo"
        }
    ]
}
You would iterate over the elements of the array, then iterate over the elements of the object.
json::value& doc = /* fetch your document */;
for (auto& game : doc.at(U("gameInfo")).as_array())
{
    for (auto& p : game.as_object())
    {
        /* use p->first and p->second */
    }
}
roschuma
Apr 1, 2014 at 5:37 PM
Great, thanks.