Daniel
Daniel

Reputation: 4342

parse json data with javascript

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);
  }
});

Upvotes: 1

Views: 2013

Answers (1)

James Allardice
James Allardice

Reputation: 165951

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.

Upvotes: 5

Related Questions