Display JSON as HTML [closed] Display JSON as HTML [closed] json json

Display JSON as HTML [closed]


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.

  1. Wrap your formatted JSON in code blocks and give them the "prettyprint" class.
  2. Include prettify.js in your page.
  3. Make sure your document's body tag calls 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.