简体   繁体   English

从javascript中的JSON对象读取值

[英]Reading values from JSON objects in javascript

I have the following JS code: 我有以下JS代码:

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

"alert(response)" prints this: “ 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}   

while "alert(dataset)" gives "undefined". 而“ alert(dataset)”给出“ undefined”。 I have tried to use 我尝试使用

     var dataset = response["data"]; 

but it did not work as well. 但效果不佳。 I want to get the data array from the JSON object. 我想从JSON对象获取数据数组。 How can i do that. 我怎样才能做到这一点。 Thanks 谢谢

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

Seeing that you got alert to show response, it's a string, not yet an object. 看到您有警报显示响应时,它是一个字符串,而不是一个对象。

You need to parse it with JSON.parse() 您需要使用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);

Here's a sample 下面是一个示例

尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM