{
"data": [{
"data": [{
"Part": "1.75 L ICON (Glass)",
"ProductionCounts": 1012620
}, {
"Part": "1.75 L Marg Mix (PET)",
"ProductionCounts": 1003278
}, {
"Part": "1.75 L Authentics (PET)",
"ProductionCounts": 457615
}, {
"Part": "1.0 L Margarita Mix / PET",
"ProductionCounts": 660982
}, {
"Part": "other",
"ProductionCounts": 1571985
}]
}, ],
"dateArray": ["2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01", "2011-05-01", "2011-06-01", "2011-07-01", "2011-08-01", "2011-09-01", "2011-10-01", "2011-11-01"],
"xAxis": "Part",
"yAxis": "ProductionCounts",
"interestingMoments": []
}
我想访问json对象的值。每次获取json对象时,json对象的字段名称都会不同,因此我将xAxis和yAxis中的字段名称作为单独发送。
当我尝试访问jsonData.data [0] .data [0] .xAxis时,它给了我undefined而不是value。 我无法像这样访问,因为每次字段名称都不同,所以我试图通过变量jsonData.data [0] .data [0] .Part。
来访问它。答案 0 :(得分:2)
jsonData.data[0].data[0][jsonData.xAxis]
和jsonData.data[0].data[0][jsonData.yAxis]
答案 1 :(得分:1)
你应该像这样使用json
var a = {
"data": [{
"data": [{
"Part": "1.75 L ICON (Glass)",
"ProductionCounts": 1012620
}, {
"Part": "1.75 L Marg Mix (PET)",
"ProductionCounts": 1003278
}, {
"Part": "1.75 L Authentics (PET)",
"ProductionCounts": 457615
}, {
"Part": "1.0 L Margarita Mix / PET",
"ProductionCounts": 660982
}, {
"Part": "other",
"ProductionCounts": 1571985
}]
}, ],
"dateArray": ["2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01", "2011-05-01", "2011-06-01", "2011-07-01", "2011-08-01", "2011-09-01", "2011-10-01", "2011-11-01"],
"xAxis": "Part",
"yAxis": "ProductionCounts",
"interestingMoments": []
};
a.data[0].data[0][a.xAxis] // for access part values
a.data[0].data[0][a.yAxis] // for acsess ProductionCounts values
答案 2 :(得分:0)
答案 3 :(得分:0)
试试这个:
var data={
"data": [{
"data": [{
"Part": "1.75 L ICON (Glass)",
"ProductionCounts": 1012620
}, {
"Part": "1.75 L Marg Mix (PET)",
"ProductionCounts": 1003278
}, {
"Part": "1.75 L Authentics (PET)",
"ProductionCounts": 457615
}, {
"Part": "1.0 L Margarita Mix / PET",
"ProductionCounts": 660982
}, {
"Part": "other",
"ProductionCounts": 1571985
}]
}, ],
"dateArray": ["2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01", "2011-05-01", "2011-06-01", "2011-07-01", "2011-08-01", "2011-09-01", "2011-10-01", "2011-11-01"],
"xAxis": "Part",
"yAxis": "ProductionCounts",
"interestingMoments": []
};
console.log(data.xAxis);
console.log(data.yAxis);
答案 4 :(得分:0)
我会从冗余的“数据”对象中解开它。
http://jsfiddle.net/turiyag/cQNPm/
之后它看起来更干净,并且工作得很好。您的JSON对象也失败了JSLint。在发布此处之前,始终通过JSLint或类似产品运行您的代码。
log("jsonData.data[0][jsonData.yAxis]: " + jsonData.data[0][jsonData.yAxis]);