How to use JSON Path to query any JSON object.
For example, consider below simple JSON, if you want to query JSON we can use simply query as this.obj.name or this.obj.id to access to the JSON
this.obj ={
id: 1,
"name": "balaji"
}
For array object we can use index, for ex: this.objData[0].id. For more JSON path to find we can refer https://jsonpathfinder.com/
this.objData = {
data: [
{
"id": 1,
"name": "Balajiprasad",
"age": 18,
"address": {
"state": "TN",
"country": "India"
}
},
{
"id": 2,
"name": "prasad",
"age": 28,
"address": {
"state": "Tx",
"country": "US"
}
}
]}
In angular project, if we need to use JSON path dynamically then we can refer the jsonpath library Ref: https://www.npmjs.com/package/jsonpath
Steps to use,
1. Add "json-path" in package.json file under dependencies
"dependencies": {
"jsonpath": "1.1.1"
}
2. Add reference of "json-path" directly in component. No need to specify in App.module
import * as jp from 'jsonpath'
3. Use the JSON path in code , need to use $.. (double dots)
let state = jp.query(this.objData, '$..data[0].address.state')