Use the JSON. stringify function to Display formatted JSON in HTML. If you have unformatted JSON It will output it in a formatted way. Or Use <pre> tag for showing code itself in HTML page and with JSON.
The key function that enables us to convert JSON to HTML at runtime is JSON. parse() . The JSON. parse() method takes textual JSON data and converts it to a JavaScript object.
Declare a JSON object and store it into variable. Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON.
Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
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, e.g.:
<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 loadsYou 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.
I think you meant something like this: JSON Visualization
Don't know if you might use it, but you might ask the author.
something like this ??
pretty-json
https://github.com/warfares/pretty-json
live sample:
http://warfares.github.com/pretty-json/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With