I'm trying to parse some nested json returned by an api call. Below is a simplified version of what is being returned.
{
"Includes":{
"Products":{
"P123456":{
"Brand":{},
"Description":"ipsem lorem",
"Statistics":
[
"Author":"John Smith",
"IsFeatured":false,
"Total": 3
]
}
}
}
}
I've tried several different syntaxes to get what I need where product_code = "P123456"
data.Includes.Products.product_code.Statistics
data.Includes.Products[product_code].Statistics
I've also tried using 'get' and 'eval' to no avail. The error response is always the same
application.js:1639 Uncaught TypeError: Cannot read property 'Statistics' of undefined
I know the product code is correct as I have console logged it. I have also successfully console.logged
data.Includes.Products["P123456"].Statistics
How can I access the data nested under the product code, "P123456" ? The project uses zepto and not jQuery.
3 Answers 3
Object.keys(data.Includes.Products) will return an array of keys under products.
If you want the first one Object.keys(data.Includes.Products)[0].
Statistics can be retrieved
var key = Object.keys(data.Includes.Products);
var statistics = data.Includes.Products[key].Statistics;
Pure JavaScript ... no libraries.
PS. Your JSON is malformed. That "Statistics" array is going to cause tears.
3 Comments
With valid data structure, you can access it via
object.Includes.Products.P123456
or
object.Includes.Products[product_code]
var object = {
"Includes": {
"Products": {
"P123456": {
"Brand": {},
"Description": "ipsem lorem",
"Statistics": { // its an object, not an array
"Author": "John Smith",
"IsFeatured": false,
"Total": 3
}
}
}
}
},
product_code = 'P123456';
document.write('<pre>' + JSON.stringify(object.Includes.Products.P123456, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(object.Includes.Products[product_code], 0, 4) + '</pre>');
Comments
Did you already tried this? data.Includes.Products.P123456.Statistics ? It looks like property and not a indexed string.
Comments
Explore related questions
See similar questions with these tags.