简体   繁体   English

如何在Javascript中解析JSON字符串?

[英]How to parse a JSON string in Javascript?

I imagine this is really basic and I'm missing something obvious. 我想这真的很基础,但我缺少明显的东西。

I want to access the values in a variable called graph_data which is holding the following JSON object: 我想访问名为graph_data的变量中的值,该变量持有以下JSON对象:

graph_data= {"data":[0,0,0,0,0,0,0.1,0.4,0,0,8.2,7,5.1,0,0,0,0,0,0,0,0,0,0,0,0]}

When I try to get graph_data.data.length I get an error that graph_data.data is "undefined". 当我尝试获取graph_data.data.length时,我收到一个错误,指出graph_data.data为“未定义”。

I can't seem to get graph_data.data[0] to return anything either. 我似乎也无法使graph_data.data [0]返回任何内容。

What am I missing here? 我在这里想念什么?

Your code works fine: 您的代码工作正常:

graph_data = {"data":[0,0,0,0,0,0,0.1,0.4,0,0,8.2,7,5.1,0,0,0,0,0,0,0,0,0,0,0,0]};
console.log(graph_data.data.length); // Outputs 25

Are you sure you have an object literal and not a string? 您确定您有对象文字而不是字符串吗?

If you have the latter you need to parse it with JSON.parse : 如果有后者,则需要使用JSON.parse进行解析:

graph_data = JSON.parse('{"data":[0,0,0,0,0,0,0.1,0.4,0,0,8.2,7,5.1,0,0,0,0,0,0,0,0,0,0,0,0]}');

You'll need a parser for older browsers without native JSON support like json2.js 对于没有本机JSON支持(例如json2.js)的旧版浏览器,您将需要一个解析器

Works for me... 为我工作...

graph_data= {"data":[0,0,0,0,0,0,0.1,0.4,0,0,8.2,7,5.1,0,0,0,0,0,0,0,0,0,0,0,0]};

for (var i = 0; i < graph_data.data.length; i++){
    $("body").append(graph_data.data[i]+"<br/>");
}

http://jsfiddle.net/mtDaH/ http://jsfiddle.net/mtDaH/

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

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