2013-02-11 123 views
0
{ 
    "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來訪問它。

回答

0

爲X軸,只是這應該工作:

console.log(jsondata.xAxis); 

在這裏看到:jsFiddle

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

我會從冗餘「數據」對象,解開它。

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

它看起來更清潔之後,和工作得很好。您的JSON對象也失敗了JSLint。在發佈之前,請始終通過JSLint或類似產品運行您的代碼。

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