Children
As mentioned in the introduction, each cJobject is either a key/value pair or is the parent of some more cJobjects. Accessing the children of a cJobject is straightforward, and as close to the JavaScript as possible within the confines and rules of the VBA language syntax.
By key , for example
job.child("somekey")
or by childIndex
job.children(1)
This is roughly equivalent to job.somekey
or job[0]
in JavaScript except that cjobject has a childIndex for both array members and regular objects (JavaScript only has indices for Arrays), and the cJobject index starts at 1 (JavaScript starts at 0)
Grandchildren
You can access grandchildren and so on in a couple of ways too
job.child("achild").child("agrandchild").child("agreatgrandchild")
is equivalent to
job.child("achild.agrandchild.agreatgrandchild")
which is close to the JavaScript
job.achild.agrandchild.agreatgrandchild
You can also mix index and named keys, so
job.children(1).child("name")
is equivalent to
job.child("1.name")
and the JavaScript equivalent
job[0].name
Arrays
As mentioned arrays are not really much different to regular objects, except that their key is the same value as their childIndex.
Using the test data from cJobject deep dive here’s an example of extracting and stringifying the the first array member
Set child = job.children(1) Debug.Print child.stringify {"name":"john","age":25}
We can print the value of the name property of the first array member
Debug.Print job.children(1).child("name").value john
Which is equivalent to this
Debug.Print job.child("1.name").value john
Note that we can always stringify (convert to JSON) any cJobject – even a single property
Debug.Print job.child("1.name").stringify {"name":"john"}
How many children
You can test if a cJobect has children like this
if (job.hasChildren) then ...
The number of children is
job.children.count
job.hasChildren
is equivalent to job.children.count > 0
. In JavaScript you could only do this test ( if (job.length > 0)
) on an Array. For an object you would need to say … if (Object.keys(job).length > 0)
Testing if a child exists
Accessing a child that doesn’t exist will return Nothing, so you can simply test any of the syntax already mentioned for Nothing
.
if (not job.child("2.age") is nothing) then ...
for convenience, I provide an isSomething()
function also, so the above is equivalent to
if (isSomething (job.child("2.age") ) ) then ...
This is roughly equivalent to the JavaScript
if(typeof job[1].age === typeof undefined) { ...
except that JavaScript will throw an error if job is not an Array, or element 1 does not exist, only making a successful test on the final property – age. cJobject will not fail, but return Nothing
.
Now let’s look at some more cJobject topics.
For more on this see How to use cJobject