有没有办法使用 JavaScript 在网页中漂亮地打印 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4739749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to pretty-print JSON in a web page using JavaScript?
提问by Hot Licks
Seems to me that pretty-printing JSON 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?
在我看来,漂亮的打印 JSON 是一项足够简单的任务,JavaScript 应该能够处理它。有没有人写过(或遇到过)一个 JavaScript 函数来做到这一点?
采纳答案by Hot Licks
What I ended up doing is installing the JSONView add-on for Mozilla. Not perfect, but it gets done what I needed done.
我最终做的是为 Mozilla 安装 JSONView 插件。不完美,但它完成了我需要完成的工作。
回答by mgamer
An easy way to do this is to execute:
一个简单的方法是执行:
JSON.stringify(data, null, " ");
where datais the json object you want to print pretty.
其中data是您想要漂亮打印的 json 对象。
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.
不过,并非每个浏览器都包含 JSON。您可以包含 Douglas Crockford 的 json.js,如果浏览器本身不支持,它会添加全局 JSON 对象。
回答by vadimk
take a look at vkbeautify.js plugin
看看 vkbeautify.js 插件
http://www.eslinstructor.net/vkbeautify/
http://www.eslinstructor.net/vkbeautify/
it provides pretty print for both JSON and XML text.
它为 JSON 和 XML 文本提供了漂亮的打印。
written in plain javascript, small and fast.
用普通的 javascript 编写,小巧而快速。
回答by smk
I use this bookmarklet code on my browsers to make the JSON paragraph readable
我在浏览器上使用此书签代码使 JSON 段落可读
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
添加书签很容易 - 右键单击书签栏 - 添加/新建 - 提供名称并将 js 粘贴到 url / 位置框中
As current day browsers are putting the json response in a <pre>tag inside, i use body.firstChild
由于当前的浏览器将 json 响应放在<pre>里面的标签中,我使用body.firstChild
回答by Rick
You can give this a try it will add in some nice CSS.
你可以试试这个,它会添加一些漂亮的 CSS。
<pre style="font-family: Courier;background: #f4f4f4;border: solid 1px #e1e1e1;float: left;width: auto;">
JSON.stringify(data, null,' ').replace('[', '').replace(']', '')
</pre>
回答by Amol Katdare
回答by capdragon
If you want this for yourself (debugging purposes) you can use Greasemonkey: http://misc.slowchop.com/misc/wiki/HumanReadableJSONGreasemonkey
如果你自己想要这个(调试目的),你可以使用 Greasemonkey:http: //misc.slowchop.com/misc/wiki/HumanReadableJSONGreasemonkey
If you want the output for your users: http://jsonformatter.curiousconcept.com/
如果你想为你的用户输出:http: //jsonformatter.curiousconcept.com/

