0

Hi I have a JSON string that looks like this:

{"2000":["1", "2", "3"],"2001":["1", "2", "3"],"2002":["1", "2", "3"]}

The string above comes from the "backend" and my JavaScript function receives the JSON string as a parameter, which is called backendData.

Looping through the parameter as below, gives the following result.

for (key in backendData) {
    alert(key);
}

Three alertboxes with the values: 2000, 2001 and 2002.

The problem is that I can't figure out how to access the string array for each of the "parent" elements. Using syntax key[0] etc. gives me the character at index 0 in the string which in all three cases are "2".

Help needed.

/Michael

2 Answers 2

2

This loops over all the values. Remember backendData is just a javascript object.

for (key in backendData) {
   for (x in backendData[key])
    alert(backendData[key][x]);
}

or in your example data this would work

for (key in backendData) {
   alert(backendData[key][0];
   alert(backendData[key][1];
   alert(backendData[key][2];
}
2
  • Well gor me somewhat further, although the inner loop gives me the index position and not the actual value, so I get 0, 1 and 2 in the inner loop alert box values. Commented May 27, 2011 at 10:38
  • OK the alert in your inner loop should be backendData[key][x] instead of just x as x is aparently just the index. Confused me but lead me to the solution. Thanks. Commented May 27, 2011 at 10:47
2

I think you want

backendData[key]

since you want to look up a mapping within the backendData map. key[0] indexes something inside of key (as a character array), which isn't what you're after as you discovered.

1
  • Great gow me 1 step further returns the string for the key as 1,2,3 how do I parse that into an array ? Commented May 27, 2011 at 10:37

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.