Prettify json data in textarea input Prettify json data in textarea input json json

Prettify json data in textarea input


The syntax highlighting is tough but check out this fiddle for pretty printing a json object entered in a text area. Do note that the JSON has to be valid for this to work. (Use the dev console to catch errors.) Check jsLint for valid json.

The HTML:

<textarea id="myTextArea" cols=50 rows=10></textarea><button onclick="prettyPrint()">Pretty Print</button>

The js:

function prettyPrint() {    var ugly = document.getElementById('myTextArea').value;    var obj = JSON.parse(ugly);    var pretty = JSON.stringify(obj, undefined, 4);    document.getElementById('myTextArea').value = pretty;}

First try simple input like: {"a":"hello","b":123}

Simple pretty printing of JSON can be done rather easily. Try this js code: (jsFiddle here)

// arbitrary js object:var myJsObj = {a:'foo', 'b':'bar', c:[false,2,null, 'null']};// using JSON.stringify pretty print capability:var str = JSON.stringify(myJsObj, undefined, 4);// display pretty printed object in text area:document.getElementById('myTextArea').innerHTML = str;

For this HTML:

<textarea id="myTextArea" cols=50 rows=25></textarea>

And check out JSON.stringify documentation.


For the parsing step you're just going to want to JSON.parse the contents of the textarea and handle any errors from bad input.

For the formatting part of your question, Use JSON.stringify(blob, undefined, 2). Alternatively, if you need colors here is a simple JSON format/color component written in React:

const HighlightedJSON = ({ json }: Object) => {  const highlightedJSON = jsonObj =>    Object.keys(jsonObj).map(key => {      const value = jsonObj[key];      let valueType = typeof value;      const isSimpleValue =        ["string", "number", "boolean"].includes(valueType) || !value;      if (isSimpleValue && valueType === "object") {        valueType = "null";      }      return (        <div key={key} className="line">          <span className="key">{key}:</span>          {isSimpleValue ? (            <span className={valueType}>{`${value}`}</span>          ) : (            highlightedJSON(value)          )}        </div>      );    });  return <div className="json">{highlightedJSON(json)}</div>;};

See it working in this CodePen:https://codepen.io/benshope/pen/BxVpjo

Hope that helps!


Late answer but modern one, use the secret intendation parameter.

I usually go for:

JSON.stringify(myData, null, 4);


Here's the code definition, it explains it well.

stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;

/** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. */