Hi everyone,
As we looked into the basics of JSON in my previous article, lets dive into it a bit more. Earlier ,we saw how we can develop a JSON file. Its easy if you are from the Programming background. But in most of the cases , we need to extract or query Data from JSON files. This process is called JSON Path Query.
JSON Path Querying using Dot Notation
For those of you who have worked using Terraform, this would be easily relatable. When you have a large file, we use ‘.’ as in we are filtering the data for the final value we need. Lets go through this, with a sample Skeleton code. JSON code is basically more or less , a complex version of this!
{
"name": "Linu",
"gender": "Female",
"role": "Devops Engineer",
"parents": [
{
"name": "ABC",
"gender": "Male"
},
{
"name": "XYZ",
"gender": "Female"
}
]
}
Now here:
- If I wanted to fetch my name, ie. the value in the pair, then I know that the key is to pass the key as — Query ->name => The output would be -> Linu
- The output comes within ” [ ]” .
Now lets see into a much more complex example.
Arrays and Lists in JSON
Lets take the same example:
{
"name": "Linu",
"gender": "Female",
"role": "Devops Engineer",
"parents": [
{
"name": "ABC",
"gender": "Male"
},
{
"name": "XYZ",
"gender": "Female"
}
]
}
For the object “parents”, It is an array of objects. Each object has got 2 attributes for it as well. So how do call the objects in an array. Its just as easy as calling the object name.
Here, it returns an Array of objects , which is fine. But what if we want to fine tune it based on some filters maybe? . In that case, we would have to go through the objects in the Array.
Continuing with the complex example, I want to find the name of my Male parent. So definitely multiple things required here.
One, we need to iterate through all the objects of the Array —
This can be achieved using ‘ @ ’
Two, we need to find the gender by passing the name attribute —
This can be done using a filter object like ‘?’
To combine both of these we do a query like :
So what exactly happens here?
- parent is an array , which return the respective objects.
- To use some filters on the parent object, we pass it as an argument — Starts with ‘?’ and passing the parameter based on which we want to filter.
- To filter objects, we need to iterate through all objects of the Array , which is done using ‘ @ ‘ and then using DOT notation, we check if the key is ‘name’ has the value “ABC”.
- Once it identifies the object , it filters out the gender of that particular object. Fine tuning done!
There are plenty of options to filter out or even manipulate the output. For a later time :)
Kindly let me know if you enjoyed this and any other suggestions that you have so that I can work on it :)
Too-da-loo!