![](/img/trans.png)
[英]Javascript: Access nested values in JSON data using dynamic variable names
[英]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
我知道產品代碼是正確的,因為我已在控制台上對其進行了記錄。 我也已經成功console.logged
data.Includes.Products["P123456"].Statistics
如何訪問嵌套在產品代碼“ P123456”下的數據? 該項目使用zepto而非jQuery。
使用有效的數據結構,您可以通過訪問
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>');
Object.keys(data.Includes.Products)
將返回product下的一組鍵。
如果要第一個Object.keys(data.Includes.Products)[0]
。
可以檢索統計數據
var key = Object.keys(data.Includes.Products);
var statistics = data.Includes.Products[key].Statistics;
純JavaScript ...沒有庫。
PS。 您的JSON格式錯誤。 “統計”數組將引起眼淚。
你已經嘗試過了嗎? data.Includes.Products.P123456.Statistics
嗎? 它看起來像屬性,而不是索引字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.