有关如何将JSON嵌入HTML页面的任何建议,其中JSON格式为人类可读的样式?例如,当您在浏览器中查看XML时,大多数浏览器都会显示XML格式(缩进,正确的换行符等).我想要与JSON相同的最终结果.
颜色语法突出显示将是一个奖励.
谢谢
Joh*_*ohn 141
您可以将JSON.stringify函数与未格式化的JSON一起使用.它以格式化的方式输出它.
JSON.stringify({ foo: "sample", bar: "sample" }, null, 4)
Run Code Online (Sandbox Code Playgroud)
这转变
{ "foo": "sample", "bar": "sample" }
Run Code Online (Sandbox Code Playgroud)
成
{
"foo": "sample",
"bar": "sample"
}
Run Code Online (Sandbox Code Playgroud)
现在,数据是一种可读格式,您可以使用@A建议的Google Code Prettify脚本.征收颜色代码吧.
值得补充的是,IE7和旧版浏览器不支持JSON.stringify方法.
Red*_*ter 76
如果你是故意显示它为最终用户,包裹在JSON文本<PRE>
和<CODE>
标签,如:
<html>
<body>
<pre>
<code>
[
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
},
{
color: "cyan",
value: "#0ff"
},
{
color: "magenta",
value: "#f0f"
},
{
color: "yellow",
value: "#ff0"
},
{
color: "black",
value: "#000"
}
]
</code>
</pre>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
否则我会使用JSON Viewer.
A. *_*evy 64
对于语法高亮,使用代码美化.我相信这就是StackOverflow用于代码突出显示的内容.
prettyPrint()
在加载时调用您将使用您在页面中布局的格式突出显示语法JSON.请看这里的例子.所以如果你有这样的代码块:
<code class="prettyprint">
var jsonObj = {
"height" : 6.2,
"width" : 7.3,
"length" : 9.1,
"color" : {
"r" : 255,
"g" : 200,
"b" : 10
}
}
</code>
Run Code Online (Sandbox Code Playgroud)
它看起来像这样:
var jsonObj = {
"height" : 6.2,
"width" : 7.3,
"length" : 9.1,
"color" : {
"r" : 255,
"g" : 200,
"b" : 10
}
}
Run Code Online (Sandbox Code Playgroud)
这对缩进没有帮助,但其他答案似乎正在解决这个问题.
war*_*res 29
这样的事情?
漂亮,JSON
https://github.com/warfares/pretty-json
现场样本:
http://warfares.github.com/pretty-json/