Display JSON as HTML
Any recommendations on how to embed JSON in an HTML page with the JSON formatted in a human readable style? For example, when you view XML in a browser, most browsers display the XML formatted (indented, proper line breaks, etc). I'd like the same end result for JSON.
Color syntax highlighting would be a bonus.
Thanks
You can use the JSON.stringify function with unformatted JSON. It outputs it in a formatted way.
JSON.stringify({ foo: "sample", bar: "sample" }, null, 4)
This turns
{ "foo": "sample", "bar": "sample" }
into
{
"foo": "sample",
"bar": "sample"
}
Now the data is a readable format you can use the Google Code Prettify script as suggested by @A. Levy to colour code it.
It is worth adding that IE7 and older browsers do not support the JSON.stringify method.
If you are deliberately displaying it for the end user, wrap the JSON text in <PRE>
and <CODE>
tags, eg:
<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>
Otherwise I would use JSON Viewer.
For the syntax highlighting, use code prettify. I believe this is what StackOverflow uses for its code highlighting.
prettyPrint()
when it loads You will have syntax highlighted JSON in the format you have laid out in your page. See here for an example. So if you had a code block like this:
<code class="prettyprint">
var jsonObj = {
"height" : 6.2,
"width" : 7.3,
"length" : 9.1,
"color" : {
"r" : 255,
"g" : 200,
"b" : 10
}
}
</code>
It would look like this:
var jsonObj = {
"height" : 6.2,
"width" : 7.3,
"length" : 9.1,
"color" : {
"r" : 255,
"g" : 200,
"b" : 10
}
}
This doesn't help with the indenting, but the other answers seem to be addressing that.
链接地址: http://www.djcxy.com/p/48218.html上一篇: mtree java脚本不能在IE中工作
下一篇: 将JSON显示为HTML