Display JSON as HTML

John Muchow picture John Muchow · May 19, 2009 · Viewed 411.7k times · Source

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

Answer

John picture John · Nov 28, 2011

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.