簡體   English   中英

從javascript中的JSON對象讀取值

[英]Reading values from JSON objects in javascript

我有以下JS代碼:

var response = loadXMLDoc();
var dataset = response.data;
alert(response);
alert (dataset);

“ alert(response)”打印:

{"labels":["-inf - 10","10 - 20","20 - 30","30 - 40","40 - 50","50 - 60","60 - 70","70 - 80","80 - 90","90 - 100","100 - 110","110 - 120","120 - 130","130 - 140","140 - 150","150 - 160","160 - +inf"],"data":[3,8,7,3,7,6,6,7,5,4,10,7,4,4,7,2,0],"count":16}   

而“ alert(dataset)”給出“ undefined”。 我嘗試使用

     var dataset = response["data"]; 

但效果不佳。 我想從JSON對象獲取數據數組。 我怎樣才能做到這一點。 謝謝

使用var y = JSON.parse(response); alert(y["data"]) var y = JSON.parse(response); alert(y["data"])

看到您有警報顯示響應時,它是一個字符串,而不是一個對象。

您需要使用JSON.parse()進行解析

//load your response
var response = loadXMLDoc(),
    dataset;

//parse response
response = JSON.parse(response);

//assign data to dataset
dataset = response.data;

//Hit F12 to see the console
console.log(response);
console.log(dataset);

下面是一個示例

嘗試這個

var dataset = eval('(' + responce.data + ')');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM