5

I'm trying to create a JS app with the following functionality: A button that gets a JSON document and displays that text. I'm going through an Elasticsearch tutorial, and there is indeed valid JSON at the url I provide:

{"_index":"planet","_type":"hacker","_id":"xfSJlRT7RtWwdQDPwkIMWg","_version":1,"exists":true, "_source" : {"handle":"mark","hobbies":["rollerblading","hacking","coding"]}}

When using the code below...I get an alert of

[object Object]

instead of an alert with the full JSON. I'm planning to take the steps next of actually selecting part of the JSON, but I'd like to at least see the full document first...

Any ideas? Thank you in advance!

<!DOCTYPE html>
<html lang="en">
<head><title>Demo</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /></head>

<body>
  <input id="testbutton" type="button" value="Test" />
  <p id="results">results appended here: </p>

<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#testbutton").click(function() {
        $.ajax({
            url: 'http://localhost:9200/planet/hacker/xfSJlRT7RtWwdQDPwkIMWg',
            dataType: 'json',
            success: function(data) {
                $("#results").append('all good');
                alert(data);
            },
             error: function() {
                $("#results").append("error");
                alert('error');
            }
        });
    });
});
</script>
</body>
</html>
allstar
  • 1,155
  • 4
  • 13
  • 29

4 Answers4

17

Use alert(JSON.stringify(data));

Matt
  • 74,352
  • 26
  • 153
  • 180
kul_mi
  • 1,131
  • 5
  • 15
  • 33
2

jQuery tries to "best guess" the data format it receives, and parse it for you.

That's exactly what you're seeing. jQuery has already parsed the JSON into an object for you. To see the JSON representation, you can stringify the data again;

alert(JSON.stringify(data));

... or, you can tell jQuery not to parse the response in the first place, passing dataType: "string" as one of the options. data will then be the JSON representation, and you'll have to JSON.parse(data) to turn it into an object.

Matt
  • 74,352
  • 26
  • 153
  • 180
0

You are getting the JSON converted to a javascript object from which you can access the individual properties using the . operator like

alert(data._type);
shyam
  • 9,134
  • 4
  • 29
  • 44
0

Simple!

alert() calls .toString() on the object which returns "[object Object]".

Use console.log(data), right-click and goto the console (or hit F12).

Or just do as the others: alert(JSON.stringify(data));

Matt
  • 74,352
  • 26
  • 153
  • 180
Leonard Pauli
  • 2,662
  • 1
  • 23
  • 23