Search code examples
pythonxpathjsonpath

path syntax for traversing python objects


Is there an expression-based tool for querying python complex objects the same way one can do using XPath for XML or jsonpath for JSON?

I thought about serializing my object to JSON and then using jsonpath on it, but it seems to be a clumsy way of doing that.


Solution

  • You can use built-in library json to import json as a nested dictionary and traverse it using dictionary notation - root['level1_object']['level2_object']. JSON-compatible object types are of course loaded as corresponding Python types.

    For other types of data there are other libraries, which mostly behave in similar fashion.

    My new favourite is Box, which allows you to traverse nested dictionaries using a dot notation.