Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prettify json data in textarea input

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.

like image 801
archytect Avatar asked Oct 12 '14 00:10

archytect


People also ask

How do I prettify JSON?

Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.

How do I prettify JSON in node JS?

If you just want to pretty print an object and not export it as valid JSON you can use console. dir() . It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.

What is JSON beautifier & Validator?

The JSON Validator & Formatter helps debugging JSON data by formatting and validating JSON data against ECMA-404 (The JSON Data Interchange Format). HOW TO USE: Paste a JSON snippet or URL in the box or just click here to see an example. Regex.


2 Answers

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.

like image 129
Paul Sasik Avatar answered Sep 18 '22 05:09

Paul Sasik


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!

like image 32
benshope Avatar answered Sep 22 '22 05:09

benshope