jquery display formatted json

怎甘沉沦 提交于 2019-12-21 07:44:39

问题


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:


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);


来源:https://stackoverflow.com/questions/21858568/jquery-display-formatted-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!