简体   繁体   中英

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= {"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".

I can't seem to get graph_data.data[0] to return anything either.

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 :

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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