jquery display formatted json

2019-04-04 17:03发布

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 ?

1条回答
看我几分像从前
2楼-- · 2019-04-04 17:48

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);
查看更多
登录 后发表回答