JavaScript JSON Formatter with Tree View

JavaScript JSON Formatter with Tree View
Code Snippet:JSON Formatter with Tree View
Author: dede brahma arianto
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 5,293
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create JSON formatter with a tree view. It uses JSON.stringify() method to convert a JavaScript object or value to a JSON string. You can input JSON data and view it in the well-formatted collapsible tree view.

Besides this, the interface comes with all necessary controls to load JSON data, expand, and reset input fields. The textarea, buttons, and other layouts of this tool can be customized with additional CSS according to your needs.

How to Create JavaScript JSON Formatter with Tree View

1. First of all, create the HTML structure as follows:

<div class="container">
    <div id="first">
      <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="three">
      <div id="json"></div>
    </div>
  </div>  

2. After that, add the following CSS styles to your project:

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;
}
#first {
  width: 350px;
  float: left;
  margin-left: 2%;
  margin-right: 2%;
}
#two {
  width: 100px;
  float: left;
  margin-right: 2%;
  margin-left: 2%;
  padding-top: 15%;
}
#three {
  width: 680px;
  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 #05bcaf;
  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 #05bcaf;
  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: #e87376;
}
.collapse {
  background-color: #D770AD;
}
.expand {
  background-color: #F6BB42;
}
[type^="button"] {
   margin-bottom: 1.42857em; 
  width: 120px;
  margin-right: 0.625em;
  outline:none;
}
.json-viewer {
  display: inline-block;
  overflow: scroll;
  height:  563px;
  width: 600px;
	color: #656D78;
  padding: 10px 10px 10px 20px;
  background-color: #ebecec;
  border: 6px solid #05bcaf;
  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:  #05bcaf;
}

.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;
}

3. Finally, add the following JavaScript code and done.

var jsonObj = {};
var jsonViewer = new JSONViewer();
document.querySelector("#json").appendChild(jsonViewer.getContainer());

var textarea = document.querySelector("textarea");
textarea.value = JSON.stringify([
  {
    "id": "001",
    "user": "megan_F0x",
    "profile":
      {    
          "nama":"Megan Fox",
          "alamat":"Jl Nin aja dulu",
          "telepon":628123456789,
          "email":"duh@malu.co",
          "social media": 
            {
              "facebook":"megan fox",
              "twitter":"@megan_F0x"
            }
      },
    "pengalaman":[
            {
              "perusahaan":"PT Transformer",
              "daritahun": 2010,
              "sampaitahun": 2011,
              "posisi": "junior developer",
              "promosi karir": null,
              "listpekerjaan": [
                {
                  "jenis": "project base",
                  "deskripsi": "front end developer",
                  "lamapekerjaan": "6 bulan",
                  "deadline bonus": true,
                  "rekan kerja": [
                    {
                      "nama": "shia lebaouf",
                      "posisi": "lead developer",
                      "contact": 
                        {
                          "telepon" : 628890066631,
                          "email": "shia@lebaouf.com",
                          "socialmedia": {
                            "facebook": "shia lebaouf",
                            "twitter": "@shia lebaouf"
                          }
                        }
                    },
                    {
                      "nama": "josh duhamel",
                      "posisi": "senior developer",
                      "contact": 
                        {
                          "telepon" : 62345667687788,
                          "email": "josh@duhamel.com",
                          "socialmedia": {
                            "facebook": "josh duhamel",
                            "twitter": "@josh duhamel"
                          }
                        }
                    }]
                },
                {
                  "jenis": "project base",
                  "jabatan": "web developer",
                  "lamapekerjaan": "3 bulan",
                  "deadline bonus": false,
                  "rekan kerja": [
                    {
                      "nama": "stephen amell",
                      "posisi": "lead developer",
                      "contact": 
                        {
                          "telepon" : 629485765690,
                          "email": "stephen@amell.com",
                          "socialmedia": {
                            "facebook": "stephen amell",
                            "twitter": "@stephen_amell"
                          }
                        }
                    },
                    {
                      "nama": "tyler perry",
                      "posisi": "senior developer",
                      "contact": 
                        {
                          "telepon" : 62948453666,
                          "email": "tyler@perry.com",
                          "socialmedia": {
                            "facebook": "tyler perry",
                            "twitter": "@tyler perry"
                          }
                        }
                    }]
                }]
            }]
  }
]);

// 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 all! hopefully, you have successfully integrated this JSON Formatter code snippet into your project. If you have any questions or facing any issues, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X