Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery display formatted json

Hi i have a problem becouse my json isn't display as formatted json.

in my web page i have a <pre></pre> tag, it cointains json string:

json example:

{"status": "OK", "output": {"pools": [{"stats": {"bytes_used": 0, "objects": 0, "kb_used": 0}, "name": "data", "id": 0}, {"stats": {"bytes_used": 0, "objects": 0, "kb_used": 0}, "name": "metadata", "id": 1}, {"stats": {"bytes_used": 0, "objects": 0, "kb_used": 0}, "name": "rbd", "id": 2}], "stats": {"total_used": 63330648, "total_space": 125604864, "total_avail": 62274216}}}

i use jquery script to format it:

var jsonPretty = JSON.stringify($(this).text(), null, '\t');
$(this).text(jsonPretty);

but itsn not working the result is:

"{\"status\": \"OK\", \"output\": {\"pools\": [{\"stats\": {\"bytes_used\": 0, \"objects\": 0, \"kb_used\": 0}, \"name\": \"data\", \"id\": 0}, {\"stats\": {\"bytes_used\": 0, \"objects\": 0, \"kb_used\": 0}, \"name\": \"metadata\", \"id\": 1}, {\"stats\": {\"bytes_used\": 0, \"objects\": 0, \"kb_used\": 0}, \"name\": \"rbd\", \"id\": 2}], \"stats\": {\"total_used\": 63330648, \"total_space\": 125604864, \"total_avail\": 62274216}}}"

how can i format it to display nice formatted json ?

like image 930
vardius Avatar asked Feb 18 '14 15:02

vardius


People also ask

How can you parse JSON via jQuery?

The jQuery parseJSON() method takes a JSON string and returns a JavaScript object. The specified JSON string must follow the strict JSON format. Passing an incorrect string will cause a JS exception. As similar to the above strings, multiple other malformed strings will cause an exception.

What does jQuery getJSON return?

The jQuery. getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. The method returns XMLHttpRequest object.

What is parseJSON?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.


1 Answers

JSON.stringify takes an object, but you are passing it a string. To use this approach, you would need to turn your string into an object then back into a string:

http://jsfiddle.net/yEez8/

var jsonStr = $("pre").text();
var jsonObj = JSON.parse(jsonStr);
var jsonPretty = JSON.stringify(jsonObj, null, '\t');

$("pre").text(jsonPretty);
like image 84
James Montagne Avatar answered Sep 23 '22 05:09

James Montagne