Navigation

Iteration

As per the examples in cJobject deep dive the most common navigation of the cJobject is by iteration through the children, or by direct access as covered in How to access children. However there are a few other navigation shortcuts, most of which don’t  have JavaScript equivalents.


For these tests, we’ll use slightly more complicated objects with additional levels.

Private Function getMoreData() As cJobject
    
    ' just get some vanilla json data
    Set getMoreData = JSONParse("[" & _
            "{'name':'john', 'demographics':{'age':25,'sex':'male'}}," & _
            "{'name':'mary', 'demographics':{'age':50,'sex':'female'}}" & _
        "]")

End Function

Finding the parent

Each cJobject has a parent link as well a children link, so we can access the parent’s info

Finding by key name

The find(key) method will return the first object that has a property name matching the given key. 

 Set child = job.find("name")
    Debug.Print child.fullKey
    Debug.Print child.stringify
_null.1.name
{"name":"john"}

We can be more specific – this example gets the age object from the 2nd array member

 Set child = job.find("2.demographics.age")
    Debug.Print child.fullKey
    Debug.Print child.stringify
_null.2.demographics.age
{"age":50}

Finding the parent

Each cJobject has a parent link as well a children link, so we can access the parent’s info from the child, and find a peer property.

Debug.Print job.find("2.demographics.age").parent.child("sex").stringify
{"sex":"female"}

And of course we can chain all this

Debug.Print job.find("2.demographics.age").parent.parent.child("name").stringify
{"name":"Mary"}

Finding in an Array

It can be useful to find an item in an array whose property value matches a particular value.  In this example we’ll find the property that matches the value “Mary”, and stringify the parent so we can see all the properties for Mary.

Debug.Print job.findInArray("name", "Mary").parent.stringify

{"name":"mary","demographics":{"age":50,"sex":"female"}}

Finding by value

Sometimes JSON objects can get fairly complicated and you may know the value you are looking for but not exactly the key. You can use the findByValue() method to find the first object matching the value you want to match

Debug.Print job.findByValue(50).stringify

{"age":50}

.. and you can chain this to make it more useful

Debug.Print job.findByValue(50).parent.parent.stringify

{"name":"mary","demographics":{"age":50,"sex":"female"}}

Now let’s look at some more cJobject topics.

For more on this see How to use cJobject