2

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?

4
  • 2
    Works for me... Can you show actual code that doesn't work & causes an error? Commented May 22, 2012 at 18:22
  • is this the format of the data or is it what you're expecing your're getting back from something? as is, it should work fine Commented May 22, 2012 at 18:24
  • It should work fine. Try declaring the variable with the 'var' statement - maybe you define & access the variable in different scope. Commented May 22, 2012 at 18:25
  • this is working jsfiddle.net/2bu2Z Commented May 22, 2012 at 18:26

2 Answers 2

5

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

1
  • A-ha! That was it. I needed to JSON.parse it into an object. It had become a string, I guess, because I've just switched to CakePHP 2.0 and switched to the new XML method Xml::toArray, which renders XML to a string and not to a JSON object. JSON.parse was it -- it's all working and plotting my jquery charts. Many thanks!! Commented May 22, 2012 at 18:35
0

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/

1
  • Thanks for taking a look Homer. Much appreciated! Commented May 22, 2012 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.