Query JSON with JMESPath

JMESPath is a query language for JSON. It allows you to easily obtain the data you need from a JSON document. If you ever worked with JSON before, you probably know that it’s easy to get a nested value.

For example: doc["person"]["age"] will get you the nested value for age in a document that looks like this:

{
  "persons": {
    "name": "erik",
    "age": "38"
  }
}

But what if you want to extract all the age-fields from an array of persons, in a document like the one below?

{
  "persons": [
    { "name": "erik", "age": 38 },
    { "name": "john", "age": 45 },
    { "name": "rob", "age": 14 }
  ]
}

We could write a loop and loop over all the persons. Easy peasy. But loops are slow and introduce complexity to your code. This is where JMESPath comes in!

This JMESPath expression will get the job done: persons[*].age. It will return an array with all the ages: [38, 45, 14].

Say you want to filter the list, and only get the ages for people named ‘erik’. You can do so with a filter: persons[?name=='erik'].age.

See how natural and quick this is? JMESPath is not part of the Python standard library, meaning you’ll need to install it with pip or pipenv. For example, when using pip in a virtual environment:

$ pip3 install jmespath
$ python3
Python 3.8.2 (default, Jul 16 2020, 14:00:26)
>>> import jmespath
>>> j = { "people": [{ "name": "erik", "age": 38 }] }
>>> jmespath.search("people[*].age", j)
[38]
>>>

You’re now ready to start experimenting! Make sure to try the interactive tutorial and view the examples on the JMESPath site!


If you liked this page, please share it with a fellow learner: