0

Possible Duplicate:
How to parse json string to javascript object

I am trying to get the values of returned JSON object by using javascript.

returned data

data: "[{"userID":"35047","testID":"5","subject":"1"..and more}]

in javascript, how do I loop through the userID/testID and value...etc.

Thanks for the help

Community
  • 1
  • 1
Rouge
  • 4,181
  • 9
  • 28
  • 36

4 Answers4

6

First parse with JSON.parse() then access them like an object. Example:

var obj = JSON.parse(your_data);

then

obj[0].userID

Explanation:

  • The outer [] create an array and you can access the array elements by subscripts like obj[0].
  • The inner {} create an object, and you can access the fields by their names. Therefore obj[0].userID, obj[0].testID, etc.

Note!

JSON.parse() requires a shim (see json.js/json2.js) in IE6/IE7. It may also be missing in other legacy browsers. You can however include it for all browsers because it detects that a native JSON.parse() exists.

nalply
  • 26,770
  • 15
  • 78
  • 101
0

jQuery can parse the JSON - http://api.jquery.com/jQuery.parseJSON/

And this post will show you how to iterate over key/value pairs in an object.

How do I loop through or enumerate a JavaScript object?

Community
  • 1
  • 1
Scott S
  • 2,696
  • 16
  • 20
0

use JSON.parse()

var object = JSON.parse(jsonString);
Gung Foo
  • 13,392
  • 5
  • 31
  • 39
0

First of all you need to parse the JSON, if you are targeting only this green browsers, then you can simply do:

var myJson = JSON.parse(data);

If not you can load a extern parse library like this one and then do it the same way.

onof
  • 17,167
  • 7
  • 49
  • 85
A. Matías Quezada
  • 1,886
  • 17
  • 34