Search code examples
jsonfilterjmespath

A query to get a JSON element on an object with JMESPATH


When I have a simple JSON like:

{
    "name": "Tom",
    "age": 20
}

Is there any JMESPath query to get age only when name is Tom?

The query should get 20 with the upper JSON.

But, if the name is not Tom like:

{
    "name": "Bob",
    "age": 31
}

The query should return null.


Solution

  • In order to filter, you will need an array.
    And you can get an array from any object with the function to_array.

    Then, because you have an unique object, you can stop the projection created by the filter, and, take the first element of the array, using | [0], as explained in the pipe expressions section of the tutorial.

    So with the query:

    to_array(@)[?name == `Tom`].age | [0]
    
    • This will give 20 for the JSON
      {
        "name": "Tom",
        "age": 20
      }
      
    • This will give null for the JSON
      {
        "name": "Bob",
        "age": 31
      }