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 ?
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.
The jQuery. getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. The method returns XMLHttpRequest object.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With