DEV Community

Craig Tomkow
Craig Tomkow

Posted on

jsonparse library. Search deeply nested JSON based on keys.

jsonparse is a simple JSON parsing python library. It is used to pull out the values you need from deeply nested JSON based on the keys provided.

The main use-case for building this library is to easily extract values based on your chosen key(s) from deeply nested JSON that is returned from many API's.

Quick Example

Lets install the library to get going.

pip install jsonparse
Enter fullscreen mode Exit fullscreen mode

Now, some sample python code to show how it works.

  1. import the library
  2. instantiate the Parser class
  3. populate test data
  4. call methods to parse data with given key(s)
from jsonparse import Parser

p = Parser()

data = {
    "temperature": "+15 °C",
    "wind": "13 km/h",
    "description": "Partly cloudy",
    "forecast": [{
        "day": "1",
        "temperature": "20 °C",
        "wind": "5 km/h"
    }, {
        "day": "2",
        "temperature": "21 °C",
        "wind": "4 km/h"
    }, {
        "day": "3",
        "temperature": "25 °C",
        "wind": "4 km/h"
    }]
}

p.find_key(data, 'temperature')
['20 °C', '21 °C', '25 °C', '+15 °C']

p.find_key_chain(data, ['forecast', 'wind'])
['5 km/h', '4 km/h', '4 km/h']
Enter fullscreen mode Exit fullscreen mode

The previous code shows us calling two different methods. The first one, find_key() searches all instances of one key, returning a list of all values.

The second method, find_key_chain() searches for the ordered list of keys starting at the first level of data.

Notice, the nested list in the JSON data is handled automatically. The jsonparse library focuses on the user providing the keys to be found.

Another feature of the find_key_chain() method is to provide a wildcard * to match any.

p.find_key_chain(data, ['forecast', '*'])
['1', '20 °C', '5 km/h', '2', '21 °C', '4 km/h', '3', '25 °C', '4 km/h']
Enter fullscreen mode Exit fullscreen mode

This is a quick example of what jsonparse does.

Additional information describing all available methods and additional examples are on jsonparse github page.

I hope this little library helps someone and any feedback is welcome. Cheers!

Top comments (0)