JSON Path Traversal




Hi, all welcome to another of my lockdown blog series posts.  Today I am planning to discuss the topic of JSON path traversal. JSON Path consists of List and Dictionaries. In JSON the List and dictionaries are organized within a pair of curly brackets. In JSON  a list is created within a set of square brackets as shown below.  As shown below, the items within [] are a list of dictionaries.

JSON path is a query language that helps to parse data available in a JSON payload. For this blog post, I will use the below dictionary to discuss some simple and advance JSON path searching scenarios.

{
   "vehicle":{
      "cars":[
         {
            "brandName":"Toyota",
            "year":"2015"
         },
         {
            "brandName":"Benz",
            "year":"2015"
         }
      ]
   }
}

Now let's look at a way we can perform search operations from the below JSON payload. Let's begin. Let's say we want to obtain the name of the first vehicle, our JSON path would look like $.vehicle.cars[0].brandName. Hear the root element is represented with the $ symbol and we go from one dictionary to the next with the use of the period symbol as in $.vehicle.cars and locate the JSON path information. If our search criteria are accurate we would end up with a result as below.

[
  "Toyota"
]

Let's say we want to find out all the car details within the vehicle, then we can achieve this using a wild card character as $.vehicle.cars[*]. This JSON path search would help us obtain the below output.

[ { "brandName":"Toyota", "year":"2015" }, { "brandName":"Benz", "year":"2015" } ]

Let's take another example. Let's say we want to obtain the year of manufacture of all
the vehicles listed in our sample JSON payload. To achieve this we could use a 
search as $.[*].year. Our search result should provide an output as

[
"2015",
"2015"
]

The * represents all or any property of a dictonary.

Let's say we want to obtain the brand name of the second vehicle then we have to use the search with[] symbols to pass the array element.   Our JSON path would be $.vehicle.cars[1]. This indicates that we are looking for the second element within the first index. This would give us output as below.

[
  {
    "brandName": "Benz",
    "year": "2015"
  }
]

Let's say we want to obtain the year of make of the Toyota car.  Our JSON search would be as below. Here we first navigate from vehicle dictionary to cars and then use the ?(@. to perform a search for the Toyota and obtain the year of manufacture. 

$.vehicle.cars[?(@.brandName == 'Toyota')].year

This would provide us with a result as below.

[
  "2015"
]


Let's say we have a large collection of the vehicle models in our list of dictionaries and we want to obtain the last element. To achieve this we can use the -1: within our search. The search would be as
$.vehicle.cars.[-1:]. This would give us the result as below.

[
    {
        "brandName": "Benz",
        "year": "2015"
    }
]

Comments