Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pretty-print JSON using JavaScript

How can I display JSON in an easy-to-read (for human readers) format? I'm looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.

like image 755
Mark Avatar asked Jan 26 '11 22:01

Mark


People also ask

How do I print a pretty JSON file?

We can use the Python json module to pretty-print the JSON data. The json module is recommended to work with JSON files. We can use the dumps() method to get the pretty formatted JSON string.

What is pretty print JSON?

Pretty printing is a form of stylistic formatting including indentation and colouring. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json .

How do I enable pretty print JSON?

To enable this feature we need to call the enable() method of the ObjectMapper and provide the feature to be enabled. ObjectMapper mapper = new ObjectMapper(). enable(SerializationFeature. INDENT_OUTPUT); String json = mapper.


2 Answers

Pretty-printing is implemented natively in JSON.stringify(). The third argument enables pretty printing and sets the spacing to use:

var str = JSON.stringify(obj, null, 2); // spacing level = 2 

If you need syntax highlighting, you might use some regex magic like so:

function syntaxHighlight(json) {     if (typeof json != 'string') {          json = JSON.stringify(json, undefined, 2);     }     json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');     return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {         var cls = 'number';         if (/^"/.test(match)) {             if (/:$/.test(match)) {                 cls = 'key';             } else {                 cls = 'string';             }         } else if (/true|false/.test(match)) {             cls = 'boolean';         } else if (/null/.test(match)) {             cls = 'null';         }         return '<span class="' + cls + '">' + match + '</span>';     }); } 

See in action here: jsfiddle

Or a full snippet provided below:

function output(inp) {      document.body.appendChild(document.createElement('pre')).innerHTML = inp;  }    function syntaxHighlight(json) {      json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');      return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {          var cls = 'number';          if (/^"/.test(match)) {              if (/:$/.test(match)) {                  cls = 'key';              } else {                  cls = 'string';              }          } else if (/true|false/.test(match)) {              cls = 'boolean';          } else if (/null/.test(match)) {              cls = 'null';          }          return '<span class="' + cls + '">' + match + '</span>';      });  }    var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};  var str = JSON.stringify(obj, undefined, 4);    output(str);  output(syntaxHighlight(str));
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }  .string { color: green; }  .number { color: darkorange; }  .boolean { color: blue; }  .null { color: magenta; }  .key { color: red; }
like image 116
user123444555621 Avatar answered Oct 03 '22 05:10

user123444555621


User Pumbaa80's answer is great if you have an object you want pretty printed. If you're starting from a valid JSON string that you want to pretty printed, you need to convert it to an object first:

var jsonString = '{"some":"json"}'; var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);   

This builds a JSON object from the string, and then converts it back to a string using JSON stringify's pretty print.

like image 36
Rick Hanlon II Avatar answered Oct 03 '22 04:10

Rick Hanlon II