How to parse a JSON object from ajax call in Java Script

A couple of things:

First, your Java servlet is not really returning a “string”. When you write jsonArray.toString(), yes, you are turning the array into a string, but that is solely for the purpose of writing it across the network. HTTP is a text protocol. So, what the doGet method is actually returning, in a sense, is a HTTP response (it just happens to be as text, it could very well be binary).

With that, when a client (in this case, your JavaScript via XMLHttpRequest) makes a GET request to your server (your servlet), it is getting back the JSON response (yes, as text). Your xmlhttp.responseText variable in this case should contain the JSON you’ve shown in the question.

Calling one of:

  • JSON.parse(xmlhttp.responseText)
  • jQuery.parseJSON(xmlhttp.responseText)
  • $.parseJSON(xmlhttp.responseText)

Should all return you the same object. With this object you can access its properties the way you want to. The following should work:

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    if (xmlhttp.responseText != null) {
        var json = xmlhttp.responseText;
        var arr = JSON.parse(json);
        var data = arr[0].data;       // This is what you want to do?
        var chart = arr[0].chart;     // This is what you want to do?
        // try running alert(chart.xAxisName);
        // and so on

Side note: When you run alert(obj); where obj is a object, you are seeing [object Object] because that is how JavaScript represents objects as strings. If you want to see the internals of a JavaScript object, as others have pointed out, you are better off using console.log(obj). (Also, upgrade or switch to a better browser. You will have access to better debugging tools.)

Leave a Comment