Prettify json data in textarea input

107,085

Solution 1

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.

Solution 2

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.
 */

Solution 3

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!

Solution 4

If you are a jquery fan, you can also use this small plugin I wrote:

// The plugin
$.fn.json_beautify= function() {
    this.each(function(){
        var el = $(this),
            obj = JSON.parse(el.val()),
            pretty = JSON.stringify(obj, undefined, 4);
        el.val(pretty);
    });
};

// Then use it like this on any textarea
$('textarea').json_beautify();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea id="myTextArea" cols=50 rows=5>{"name":"John","age":30}</textarea>
<textarea id="myTextArea2" cols=50 rows=5>{"name":"Bob","age":55}</textarea>

UPD Changed code to multiselected elements.

Solution 5

I don't think that can be done with regular textareas. What you can do (and how most online code editors do it) is to create a transparent textarea that overlays on top of a div that contains the styled code. The user would still be able to type and interact with the input (and it fires the associated form events), and you can show syntax highlighting in the div that the user will visually see (see Textarea that can do syntax highlighting on the fly?)

Now as for JSON formatting, I would add custom events to the textarea so that when a user types or paste something, run it through a Javascript JSON prettifier (see How can I pretty-print JSON using JavaScript?) and then re-populate the div and textarea accordingly

Share:
107,085
archytect
Author by

archytect

Updated on July 05, 2022

Comments

  • archytect
    archytect almost 2 years

    I've searched for this particular topic and couldn't find anything similar to it. If there is please close this and give a link.

    I'm creating a json data api simulator. I want users to be able to copy and paste a json object request into a textarea where they can also modify it before sending it to the server.

    Problem is json obj copy and patses often results in extra spaces and is never aligned properly, even with the pre tag. I also want a good color scheme applied to keys and values.

    I've seen plugins, other questions and snippets of code, but they don't apply to textareas where the text is editable. Is there to keep it styled while in edit mode without it showing all the html tags that styled it? I want to be able to write it from scratch with javascript or jquery.

  • Rohidas Kadam
    Rohidas Kadam over 6 years
    JSON.stringify(obj, undefined, 4) This is what I was looking for. Thank you
  • zfj3ub94rf576hc4eegm
    zfj3ub94rf576hc4eegm almost 4 years
    how is this recursive?
  • Alex Jolig
    Alex Jolig almost 4 years
    @Luke Thank you! Missed some lines!
  • Akhil
    Akhil almost 4 years
    Yeah this is the structure of JSON.stringify() stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string