Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print plain JSON content to html page in Javascript / jQuery

Tags:

json

jquery

After getting an HTTP response in the form a JSON file, how can I handle its plain content using jQuery?

I've done this before, but I just can't figure out how right now.

I'm using this function to retrieve the JSON content.

var json = $.getJSON("test.json",  
   function(response){
           // do stuff
       }
);

Of course, I can handle the data contained in the JSON, but I'd like to handle and print its plain content, like this:

{"name": "Pepe","age" : "20"}

The following

alert(response);

Just gives me [object Object]

And this

alert(jQuery.parseJSON(json));

Just gives me null

I can't seem to find the answer anywhere. I'm pretty new to all this, so I must be using the wrong search terms, because it looks like a trivial matter.

like image 804
cangrejo Avatar asked Jul 10 '12 19:07

cangrejo


People also ask

How fetch data from JSON to HTML?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.


2 Answers

JSON.stringify is probably what you want. MDN Docs

like image 137
JohnD Avatar answered Oct 23 '22 06:10

JohnD


The callback to $.getJSON actually has 3 parameters. data, textStatus and jqXHR.

The jqXHR object contains a responseText property that contains the raw JSON string.

var json = $.getJSON("test.json",  
   function(response, status, jqXHR){
           // do stuff
           console.log(jqXHR.responseText);
       }
);
like image 20
Rocket Hazmat Avatar answered Oct 23 '22 04:10

Rocket Hazmat