How we can format or beautify JSON codes using JavaScript? Solution: See this JSON Formatter & Beautifier with Tree View, Beautify JSON Codes Online.
Previously I have shared an HTML CSS Minifier and Beautifier program, but this program is for beautifying JSON structure data. Basically, code minify and beautify is the process of compress and decompress codes. When we put codes online on server, then we have to minify that code of fast webpage loading. But later when we want to read that code then it difficult to understand because of minifying or compressing. Then we have to do use code formatter or beautifier programs to decompressing the code.
Today you will learn to create a Beautify JSON Codes Online program. Basically, there are 2 boxes for minified and beautified versions and 4 buttons for load, collapse, expand, and reset functions. There is a code block I have placed in files, by default you will see compressed codes on the minified codes section. You can experiment with the program with the help of those codes, you can beautify or format the codes by pressing the load button. When you will click on collapse then the codes will manage with a tree view, and on expand button click all codes will show again. You can reset the minified or compressed codes section by pressing the reset button, also you can just replace the codes by select and delete.
So, Today I am sharing JSON Formatter & Beautifier with Tree View. There I have used JavaScript to create the program, and the layout & styles are based on HTML CSS. This is a complete program to beautify JSON codes. You can use this program to build your online JSON formatter and beautifier. Also, you can customize the program like add save or download codes feature according to your requirement.
If you are thinking now how this JSON formatter program actually is, then see the preview given below.
Preview Of Beautify JSON Codes Online
See this video preview to getting an idea of how this code uncompress/decompress program looks like.
Now you can see this program visually, also you can see it live by pressing the button given above. If you like this, then get the source code of its.
You May Also Like:
- Folding Select Dropdown
- Random Password Generator
- JavaScript RGB Slider
- Material Login & Signup Form
JSON Formatter & Beautifier with Tree View Source Code
Before sharing source code, let’s talk about it. First I have created a div named container for placing minified codes using the form, label, and textarea tags. Then I have created another div with 4 buttons tags to placing the function buttons. After that, I have created another div for output for beautified codes.
Now using CSS I have placed all the elements in the right place, as you can see in the preview. With CSS first I gave basic values like size, position, margin, padding, etc to all the elements. There I have used width: and max-width: both tags to create a responsive design. There I have also styled those elements which dynamically created by JavaScript.
JavaScript handling the here whole functions in this program. There I have dynamically created an HTML list for beautifying codes layout and tree view feature. I have used JS if{} else{} statements to creating the functions, and I have placed a value to textarea for by default visualize codes sample. For fetching the buttons I have used document.querySelector command and used .addEventListener command for detecting the actions.
Left all other things you will understand after getting the codes, I can’t explain all in writing. For creating this program you have to create 3 files. First file for HTML, second for CSS, and the third file for JavaScript. Follow the steps to creating this program without any error.
index.html
Create an HTML file named ‘index.html‘ and put these codes given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<!DOCTYPE html> <!-- Code By Webdevtrick ( https://webdevtrick.com ) --> <html lang="en" > <head> <meta charset="UTF-8"> <title>JSON Formatter Beautifier | Webdevtrick.com</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <div id="wrap"> <form class="form"> <label class="form__label--hidden" for="msg">Input json:</label> <textarea class="form__input" class="form__input" id="msg" placeholder="Input json..." rows="6"></textarea> </form> </div> <div id="two"> <button type="button" class="load-json">Load</button> <button type="button" class="collapse">Collapse</button> <button type="button" class="expand">Expand</button> <button type="button" class="reset">Reset</button> </div> <div id="tree"> <div id="json"></div> </div> </div> <script src="function.js"></script> </body> </html> |
style.css
Now create a CSS file named ‘style.css‘ and put these codes given here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
/* Code By Webdevtrick ( https://webdevtrick.com ) */ input, textarea { display: block; outline: 0; border: 0; } input:focus, textarea:focus { transition: 0.2s; } body { background-color: #fff; font-family: 'Open Sans', Helvetica, sans-serif; } .container { width: 100%; margin: 30px auto; } #wrap { width: 350px; max-width: 90%; float: left; margin-left: 2%; margin-right: 2%; } #two { width: 100px; float: left; margin-right: 2%; margin-left: 2%; padding-top: 15%; } #tree { width: 680px; max-width: 98%; float: left; margin-left: 1%; margin-top: -12px; } .form__label { display: block; margin-bottom: 0.625em; } .form__label--hidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } .form__input { width: 100%; height: 560px; font-size: 1em; padding: 0.83333em; margin-bottom: 5px; border: 6px solid #ff5f5f; border-radius: 0.4em; background: #ebecec; color: #656D78; font-weight: 300; } .form__modal { width: 83%; font-size: 1em; padding: 0.83333em; margin-bottom: 5px; border-bottom: 6px solid #ff5f5f; border-radius: 0.4em; background: #ebecec; color: #656D78; font-weight: 300; } .load-json, .reset, .collapse, .expand, [type^="button"] { padding: 0.9375em 1.875em; border: 0; border-radius: 0.4em; color: #fff; text-transform: uppercase; font-size: 0.875em; font-weight: 400; transition: opacity 0.2s; display: block; width: 100%; } .load-json:hover, .reset:hover, .collapse:hover, .expand:hover, [type^="button"]:hover { opacity: 0.75; cursor: pointer; } .load-json { background-color: #3BAFDA; } .reset { background-color: #e60023; } .collapse { background-color: #5cb85c; } .expand { background-color: #fd9d08; } [type^="button"] { margin-bottom: 1.42857em; width: 120px; margin-right: 0.625em; outline:none; } .json-viewer { display: inline-block; overflow: scroll; height: 563px; width: 710px; max-width: 90%; color: #656D78; padding: 10px 10px 10px 20px; background-color: #ebecec; border: 6px solid #ff5f5f; border-radius: 0.4em; margin-bottom: 3px; } .json-viewer ul { list-style-type: none; margin: 0; margin: 0 0 0 1px; border-left: 3px dotted #ccc; padding-left: 2em; } .json-viewer .hide { display: none; } .json-viewer ul li .type-string, .json-viewer ul li .type-date { color: #ff5f5f; } .json-viewer ul li .type-boolean { color: #F6BB42; font-weight: bold; } .json-viewer ul li .type-number { color: #e87376; } .json-viewer ul li .type-null { color: #EC87C0; } .json-viewer a.list-link { color: #656D78; text-decoration: none; position: relative; } .json-viewer a.list-link:before { color: #aaa; content: "\25BC"; position: absolute; display: inline-block; width: 1em; left: -1em; } .json-viewer a.list-link.collapsed:before { content: "\25B6"; } .json-viewer a.list-link.empty:before { content: ""; } .json-viewer .items-ph { color: #aaa; padding: 0 1em; } .json-viewer .items-ph:hover { text-decoration: underline; } |
function.js
The last step, create a JavaScript file named ‘function.js‘ and put the codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 |
// Code By Webdevtrick ( https://webdevtrick.com ) JSONViewer = (function() { var JSONViewer = function() { this._dom = {}; this._dom.container = document.createElement("pre"); this._dom.container.classList.add("json-viewer"); }; JSONViewer.prototype.showJSON = function(json, maxLvl, colAt) { maxLvl = typeof maxLvl === "number" ? maxLvl : -1; // max level colAt = typeof colAt === "number" ? colAt : -1; // collapse at var jsonData = this._processInput(json); var walkEl = this._walk(jsonData, maxLvl, colAt, 0); this._dom.container.innerHTML = ""; this._dom.container.appendChild(walkEl); }; /** * Get container with pre object - this container is used for visualise JSON data. * * @return {Element} */ JSONViewer.prototype.getContainer = function() { return this._dom.container; }; /** * Process input JSON - throws exception for unrecognized input. * * @param {Object|Array} json Input value * @return {Object|Array} */ JSONViewer.prototype._processInput = function(json) { if (json && typeof json === "object") { return json; } else { throw "Input value is not object or array!"; } }; /** * Recursive walk for input value. * * @param {Object|Array} value Input value * @param {Number} maxLvl Process only to max level, where 0..n, -1 unlimited * @param {Number} colAt Collapse at level, where 0..n, -1 unlimited * @param {Number} lvl Current level */ JSONViewer.prototype._walk = function(value, maxLvl, colAt, lvl) { var frag = document.createDocumentFragment(); var isMaxLvl = maxLvl >= 0 && lvl >= maxLvl; var isCollapse = colAt >= 0 && lvl >= colAt; switch (typeof value) { case "object": if (value) { var isArray = Array.isArray(value); var items = isArray ? value : Object.keys(value); if (lvl === 0) { // root level var rootCount = this._createItemsCount(items.length); // hide/show var rootLink = this._createLink(isArray ? "[" : "{"); if (items.length) { rootLink.addEventListener("click", function() { if (isMaxLvl) return; rootLink.classList.toggle("collapsed"); rootCount.classList.toggle("hide"); // main list this._dom.container.querySelector("ul").classList.toggle("hide"); }.bind(this)); if (isCollapse) { rootLink.classList.add("collapsed"); rootCount.classList.remove("hide"); } } else { rootLink.classList.add("empty"); } rootLink.appendChild(rootCount); frag.appendChild(rootLink); } if (items.length && !isMaxLvl) { var len = items.length - 1; var ulList = document.createElement("ul"); ulList.setAttribute("data-level", lvl); ulList.classList.add("type-" + (isArray ? "array" : "object")); items.forEach(function(key, ind) { var item = isArray ? key : value[key]; var li = document.createElement("li"); if (typeof item === "object") { var isEmpty = false; // null && date if (!item || item instanceof Date) { li.appendChild(document.createTextNode(isArray ? "" : key + ": ")); li.appendChild(this._createSimple(item ? item : null)); } // array & object else { var itemIsArray = Array.isArray(item); var itemLen = itemIsArray ? item.length : Object.keys(item).length; // empty if (!itemLen) { li.appendChild(document.createTextNode(key + ": " + (itemIsArray ? "[]" : "{}"))); } else { // 1+ items var itemTitle = (typeof key === "string" ? key + ": " : "") + (itemIsArray ? "[" : "{"); var itemLink = this._createLink(itemTitle); var itemsCount = this._createItemsCount(itemLen); // maxLvl - only text, no link if (maxLvl >= 0 && lvl + 1 >= maxLvl) { li.appendChild(document.createTextNode(itemTitle)); } else { itemLink.appendChild(itemsCount); li.appendChild(itemLink); } li.appendChild(this._walk(item, maxLvl, colAt, lvl + 1)); li.appendChild(document.createTextNode(itemIsArray ? "]" : "}")); var list = li.querySelector("ul"); var itemLinkCb = function() { itemLink.classList.toggle("collapsed"); itemsCount.classList.toggle("hide"); list.classList.toggle("hide"); }; // hide/show itemLink.addEventListener("click", itemLinkCb); // collapse lower level if (colAt >= 0 && lvl + 1 >= colAt) { itemLinkCb(); } } } } // simple values else { // object keys with key: if (!isArray) { li.appendChild(document.createTextNode(key + ": ")); } // recursive li.appendChild(this._walk(item, maxLvl, colAt, lvl + 1)); } // add comma to the end if (ind < len) { li.appendChild(document.createTextNode(",")); } ulList.appendChild(li); }, this); frag.appendChild(ulList); } else if (items.length && isMaxLvl) { var itemsCount = this._createItemsCount(items.length); itemsCount.classList.remove("hide"); frag.appendChild(itemsCount); } if (lvl === 0) { // empty root if (!items.length) { var itemsCount = this._createItemsCount(0); itemsCount.classList.remove("hide"); frag.appendChild(itemsCount); } // root cover frag.appendChild(document.createTextNode(isArray ? "]" : "}")); // collapse if (isCollapse) { frag.querySelector("ul").classList.add("hide"); } } break; } default: // simple values frag.appendChild(this._createSimple(value)); break; } return frag; }; /** * Create simple value (no object|array). * * @param {Number|String|null|undefined|Date} value Input value * @return {Element} */ JSONViewer.prototype._createSimple = function(value) { var spanEl = document.createElement("span"); var type = typeof value; var txt = value; if (type === "string") { txt = '"' + value + '"'; } else if (value === null) { type = "null"; txt = "null"; } else if (value === undefined) { txt = "undefined"; } else if (value instanceof Date) { type = "date"; txt = value.toString(); } spanEl.classList.add("type-" + type); spanEl.innerHTML = txt; return spanEl; }; /** * Create items count element. * * @param {Number} count Items count * @return {Element} */ JSONViewer.prototype._createItemsCount = function(count) { var itemsCount = document.createElement("span"); itemsCount.classList.add("items-ph"); itemsCount.classList.add("hide"); itemsCount.innerHTML = this._getItemsTitle(count); return itemsCount; }; /** * Create clickable link. * * @param {String} title Link title * @return {Element} */ JSONViewer.prototype._createLink = function(title) { var linkEl = document.createElement("a"); linkEl.classList.add("list-link"); linkEl.href = "javascript:void(0)"; linkEl.innerHTML = title || ""; return linkEl; }; /** * Get correct item|s title for count. * * @param {Number} count Items count * @return {String} */ JSONViewer.prototype._getItemsTitle = function(count) { var itemsTxt = count > 1 || count === 0 ? "items" : "item"; return (count + " " + itemsTxt); }; return JSONViewer; })(); var jsonObj = {}; var jsonViewer = new JSONViewer(); document.querySelector("#json").appendChild(jsonViewer.getContainer()); var textarea = document.querySelector("textarea"); textarea.value = JSON.stringify([ { "links": { "self": "http://example.com/articles", "next": "http://example.com/articles?page[offset]=2", "last": "http://example.com/articles?page[offset]=10" }, "data": [{ "type": "articles", "id": "1", "attributes": { "title": "JSON:API paints my bikeshed!" }, "relationships": { "author": { "links": { "self": "http://example.com/articles/1/relationships/author", "related": "http://example.com/articles/1/author" }, "data": { "type": "people", "id": "9" } }, "comments": { "links": { "self": "http://example.com/articles/1/relationships/comments", "related": "http://example.com/articles/1/comments" }, "data": [ { "type": "comments", "id": "5" }, { "type": "comments", "id": "12" } ] } }, "links": { "self": "http://example.com/articles/1" } }], "included": [{ "type": "people", "id": "9", "attributes": { "firstName": "Dan", "lastName": "Gebhardt", "twitter": "dgeb" }, "links": { "self": "http://example.com/people/9" } }, { "type": "comments", "id": "5", "attributes": { "body": "First!" }, "relationships": { "author": { "data": { "type": "people", "id": "2" } } }, "links": { "self": "http://example.com/comments/5" } }, { "type": "comments", "id": "12", "attributes": { "body": "I like XML better" }, "relationships": { "author": { "data": { "type": "people", "id": "9" } } }, "links": { "self": "http://example.com/comments/12" } }] } ]); // textarea value to JSON object var setJSON = function () { try { var value = textarea.value; jsonObj = JSON.parse(value); } catch (err) { alert(err); } }; // load default value setJSON(); var loadJsonBtn = document.querySelector("button.load-json"); var collapseBtn = document.querySelector("button.collapse"); var expandBtn = document.querySelector("button.expand"); var resetBtn = document.querySelector("button.reset"); loadJsonBtn.addEventListener("click", function () { setJSON(); jsonViewer.showJSON(jsonObj); }); collapseBtn.addEventListener("click", function () { jsonViewer.showJSON(jsonObj, null, 1); }); expandBtn.addEventListener("click", function () { setJSON(); jsonViewer.showJSON(jsonObj); }); resetBtn.addEventListener("click", function () { document.getElementById("msg").value = ""; }); |
That’s It. Now you have successfully created JSON Formatter & Beautifier with Tree View, Beautify JSON Codes Online program. If you have any doubt or question comment down below.
Thanks For Visiting, Keep Visiting.
We found an amazing online tool that formats JSON objects. This beautifies JSON is easily readable by humans.
{
“name”:”Jhon”,
“title”:”Author”,
“country”:”USA”
}