JavaScript 解析带有动态变量的嵌套 JSON
javascript parse nested json with dynamic variable
我正在尝试解析由api调用返回的一些嵌套json。以下是所返回内容的简化版本。
{
"Includes":{
"Products":{
"P123456":{
"Brand":{},
"Description":"ipsem lorem",
"Statistics":
[
"Author":"John Smith",
"IsFeatured":false,
"Total": 3
]
}
}
}
}
我尝试了几种不同的语法来获得我需要的东西,其中 product_code = "P123456"
data.Includes.Products.product_code.Statistics
data.Includes.Products[product_code].Statistics
我也尝试使用"get"和"eval"无济于事。错误响应始终相同
application.js:1639 Uncaught TypeError: Cannot read property 'Statistics' of undefined
我知道产品代码是正确的,因为我已经控制台记录了它。我也成功地控制台登录
data.Includes.Products["P123456"].Statistics
如何访问嵌套在产品代码"P123456"下的数据?该项目使用zepto而不是jQuery。
Object.keys(data.Includes.Products)
将在产品下返回一个键数组。
如果你想要第一个Object.keys(data.Includes.Products)[0]
.
可以检索统计信息
var key = Object.keys(data.Includes.Products);
var statistics = data.Includes.Products[key].Statistics;
纯JavaScript ...没有库。
附言。您的 JSON 格式不正确。那个"统计"数组会引起眼泪。
使用有效的数据结构,您可以通过以下方式访问它
object.Includes.Products.P123456
或
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>');
你已经试过了吗? data.Includes.Products.P123456.Statistics
?它看起来像属性,而不是索引字符串。
相关文章:
- 访问嵌套函数结构中的JavaScript父函数变量
- 在变量中显示或嵌套变量:Cordova、Ionic、emailComposer
- 如何在嵌套函数jquery上保持变量的值不变
- 访问带有变量的嵌套Javascript对象
- javascript和jQuery的嵌套对象函数中的变量范围
- React:使用索引变量更新嵌套集合
- Javascript循环嵌套变量
- 嵌套循环中数组2d中的javascript变量丢失
- Node.js:用作对象嵌套元素名称的变量
- 为什么嵌套的 describe() 块不能看到在外部块中定义的变量
- jquery嵌套函数中的全局变量
- 如何从嵌套函数中访问变量
- 为局部嵌套函数中的全局变量设置值
- 在全局范围内访问嵌套变量的 Nodejs
- JsRender:如何将变量传递到嵌套模板中
- JavaScript 解析带有动态变量的嵌套 JSON
- 冒泡 从嵌套函数更新变量
- Angular JS(嵌套变量)中的绑定问题
- JavaScript-如何使用递归创建变量嵌套循环
- NodeJS -如何发送一个变量嵌套回调?(MongoDB查找查询)