通过变量获取json对象值

通过变量获取json对象值

问题描述:

{ 
    "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中的字段名称分开发送。通过变量获取json对象值

当我试图访问jsonData.data [0] .data [0] .xAxis时,它给我未定义的值而不是值。 我不能这样访问,因为字段名称每次都会有所不同,所以我试图通过变量jsonData.data [0] .data [0] .Part来访问它。

为X轴,只是这应该工作:

console.log(jsondata.xAxis); 

在这里看到:jsFiddle

试试这个:

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); 

jsonData.data[0].data[0][jsonData.xAxis]jsonData.data[0].data[0][jsonData.yAxis]

http://jsfiddle.net/vsZkR/

你应该使用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 

我会从冗余“数据”对象,解开它。

http://jsfiddle.net/turiyag/cQNPm/

它看起来更清洁之后,和工作得很好。您的JSON对象也失败了JSLint。在发布之前,请始终通过JSLint或类似产品运行您的代码。

log("jsonData.data[0][jsonData.yAxis]: " + jsonData.data[0][jsonData.yAxis]);