开发者

Is there a way to pretty-print JSON in a web page using JavaScript?

Seems to me that pretty-printing JSON 开发者_Go百科is a simple enough task that JavaScript should be able to handle it. Has anyone ever written (or run across) a JavaScript function to do this?


An easy way to do this is to execute:

JSON.stringify(data, null, "  ");

where data is the json object you want to print pretty.

Not every browser contains JSON though. You can include json.js by Douglas Crockford which add global JSON object if it is not supported natively by the browser.


I use this bookmarklet code on my browsers to make the JSON paragraph readable

javascript:(function(){document.body.firstChild.innerHTML = JSON.stringify(JSON.parse(document.body.firstChild.innerHTML), null, 4);})();

Adding a bookmarklet is easy - right click on bookmarks bar - Add/New - provide a name and paste js in url / location box

As current day browsers are putting the json response in a <pre> tag inside, i use body.firstChild


take a look at vkbeautify.js plugin

http://www.eslinstructor.net/vkbeautify/

it provides pretty print for both JSON and XML text.

written in plain javascript, small and fast.


JavaScript data formatting/pretty printer


What I ended up doing is installing the JSONView add-on for Mozilla. Not perfect, but it gets done what I needed done.


You can give this a try it will add in some nice CSS.

<pre style="font-family: Courier;background: #f4f4f4;border: solid 1px #e1e1e1;float: left;width: auto;">
    JSON.stringify(data, null,' ').replace('[', '').replace(']', '')
</pre>


If you want this for yourself (debugging purposes) you can use Greasemonkey: http://misc.slowchop.com/misc/wiki/HumanReadableJSONGreasemonkey

If you want the output for your users: http://jsonformatter.curiousconcept.com/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜