从 javascript 中的 JSON 对象读取值

Reading values from JSON objects in javascript

本文关键字:读取 对象 JSON javascript 中的      更新时间:2023-09-26

>我有以下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}   

而"警报(数据集)"给出"未定义"。我尝试使用

     var dataset = response["data"]; 

但它也没有那么奏效。我想从 JSON 对象获取数据数组。我该怎么做。谢谢

使用 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 + ')');