1

I have a proxy script that outputs json data via php, and I want to be able to manipulate this data using javascript. I have the following code, but it only gets the entire json string outputted by the php script. How do I take the data and be able to access the individual objects with in this json data?

var xmlhttp;
function loadXMLDoc(url, cfunc) {
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = cfunc;
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

loadXMLDoc("http://xxxxx.appspot.com/userbase_us.php?callback=userdata", function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var json = xmlhttp.responseText;
      alert(json);
  }
});
Daniel
  • 4,202
  • 11
  • 50
  • 68
  • possible duplicate of [how to parse json in javascript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – Polynomial Jun 08 '12 at 10:21

1 Answers1

5

You can use the native JSON.parse method:

var json = JSON.parse(xmlhttp.responseText);

Note that since this is not supported by older browsers, you will most likely want to polyfill it.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • @Mr.1.0 - Then your JSON is not valid. Update your question with an example JSON string returned by your script, or use a tool like [JSON Lint](http://jsonlint.com/) to validate it. – James Allardice Jun 08 '12 at 10:28