0

I am relatively new to javascript and very new to JSON and got the job of changing an internal website so it meets our new company needs. I am trying to access a JSON object with an array in it. This actually works pretty for most of the objects, except the array. Everytime I try to access the elements in the array I get undefined or NaN.

When I do

alert(JSON.stringify(object.data.average[0]));
I get the following output

[{"test_count2":"360","succeeded":"185"}]

so I know the objects I am trying to access are there, but when I do

alert(JSON.stringify(object.data.average[0].succeeded))
or

alert(JSON.stringify(object.data.average[0]['succeeded']))

I always get just

undefined

Am I doing something entirely wrong here? As I sad, I am a newby, so please be patient with me ;)

thanks in advance!

2
  • better to paste your whole (or atleast object.data.average) JSON data , as it seems to me that there is an array inside another array ( object.data.average[0][0] ?) Commented Oct 30, 2014 at 6:49
  • "average": { "0": [ { "test_count":"360", "succeeded":"185" } ] , "test_count":"192", "failed":"7", "succeeded":"185", "ratio":"0.5978", "id":"41", "overall_status":"1" }, Still I dont get why there is an array inside the array... Commented Oct 30, 2014 at 6:59

4 Answers 4

1

Try with JSON.stringify(object.data.average[0][0].succeeded). It seems that object.data.average[0] returns an array with a single element in it. Also, you can use console.log(object.data), instead of alert. It's way easier to see a tree representation of an object in the console on a modern web-browser, instead of alerting string values like in the old days.

Sign up to request clarification or add additional context in comments.

Comments

0

Since it's yet another array you would have to do this

object.data.average[0][0]['succeeded'];

1 Comment

No problems, happy hacking!
0

You seem to have forgotten that you have another object inside your array. Try,

alert(JSON.stringify(object.data.average[0][0].succeeded))

Comments

0

Assuming that you want to access the succeeded value from the "stringified json" , you will need to convert the string '[{"test_count2":"360","succeeded":"185"}]' which is now a plain string back to an json object.

Steps are: var str = '[{"test_count2":"360","succeeded":"185"}]'; var obj = JSON.parse(str); //This function reverses what JSON.stringify does to a json alert(obj.succeeded); //Output: 185

Hope i was clear :)

Comments

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.