In this blog, we will see how to read a complex Json having Arrays and sub JSON block.
JSON basically consist of Array => [ ] and Curly Braces => { }
Reading JSON will be easy to understand if we go step by step
Let’s start with a simple JSON object
var myJson = {
"name" : "Read Json in Javascript",
"date" : "12-Jun-2018"
}
console.log(myJson.name); // prints : Read Json in Javascript
var myArrayJson = [{
"name" : "Read Json in Javascript",
"date" : "12-Jun-2018"
}]
console.log(myArrayJson.name); // prints: undefined => as json is Array so we need to read it by index
console.log(myArrayJson[0].name); // prints: Read Json in Javascript
Now lets see combination of above examples
var jsonData = [{
"firewallName": "Palo_1",
"firewallIp": "192.168.0.104",
"lstRouterEntries": [{
"name": "default",
"routingTable": {
"routingTableIP": {
"time": "2018/07/12 07:26:50",
"staticRoute": {
"routeEntry": [{
"name": "Route1",
"destination": "192.168.1.1/32",
},
{
"name": "Route2",
"destination": "192.168.11.1/32",
}
]
}
}
}
},
{
"name": "VirtualRouter1",
"routingTable": {
"routingTableIP": {
"time": null,
"staticRoute": {
"routeEntry": [{
"name": "Router11",
"destination": "10.0.0.0/24",
}]
}
}
}
}
]
}];
Let’s say I need the value of following attributes
- firewall name
- lstRouterEntries : name
- routeEntry : name
Let’s analyze our jsonData Object.
It starts with [] so JSON object contains an Array of Object so we need to start with index.
var mainData = jsonData[0]; // this gives me whole Object inside Array
var firewallName = mainData.firewallName; // returns Palo_1
var allRouterEntry = mainData.lstRouterEntries[0]; // contains all lstRouterEntries objects
var entryName = allRouterEntry.name; returns default
var allStatRoutingEntry = allRouterEntry.routingTable.routingTableIP.staticRoute.routeEntry; // contains all objects of routeEntry
var staticRouteEntryName = allStatRoutingEntry[0].name; // gives Route1
console.log(firewallName+" : "+entryName+" : "+staticRouteEntryName);
Output:
Palo_1 : default : Route1
0 Comments