This is a relatively simple JSON object traverser: feed it either a JSON string or a nested set of dicitonaries/lists and use a path notation to access individual items.
- It supports paths separated with either
/
or any separator string you specify - It supports wildcards
*
to iterate over multiple values - Arrays/lists are accessed simply by number instaed of names e.g.
name_with_array/0/property_of_zeroth_item
- If a bad query token or data type is encountered, it will print the offending path
It is relatively naive, insomuch as it will create a new array in the output object for each wildcard used along the path. For example, here's an example of getting all subnet definitions on docker inspect <networks ...>
:
docker_network_ids = ["789af6","ec87f65"]
stdout,stderr = subprocess.Popen("docker inspect".split(" ") + docker_network_ids, stdout=subprocess.PIPE ).communicate()
# jsonwalker at play:
result = jsonlib.JSONWalker(stdout).get('*/IPAM/Config/*/Subnet')
for ipam in result: # array of subnets, though the piece we next accessed is the 'IPAM' property
for subnet in ipam: # again, array of 'Config', but it's the Subnet we accessed directly
print(subnet)
You can use a flatten=True
argument on the get()
method to attempt to intelligently flatten the results. The above becomes thus:
result = jsonlib.JSONWalker(stdout).get('*/IPAM/Config/*/Subnet', flatten=True)
for subnet in result:
print(subnet)
There are no unit tests, nor performance tests. Use at your own discretion.