JSON constructor

In this example below you will see how to do a JSON constructor with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by Larvatus, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Larvatus ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>JSON constructor</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <h1>JSON Constructor</h1>
<p>v 1.2</p>
<table id="mainTable" border="1" bordercolor="#f2f2f2" cellspacing="0">
  <tr>
    <td>
      <b>Key</b>
    </td>
    <td>
      <b>Value</b>
    </td>
  </tr>
  <tr>
    <td>
      <input id="keyfromlist" name="jsonkey" type="radio" checked>
      <label id="keyfromlistlabel" for="keyfromlist">From list</label></></br>
      <select id="keylist" size="5"></select>
      <br>
      <input id="keyfrominput" name="jsonkey" type="radio">
      <label id="keyfrominputlabel" for="jsonkey">New key</label></br>
      <input id="keynew" name="title" type="text" size="40">
    </td>
    <td>
      <input id="valtemplate" name="jsonvalue" type="radio" checked>
      <label id="valtemplatelabel" for="valtemplate">Template</label></>
      <select  id="template">
      </select>
      <br>
      <input id="valobject" name="jsonvalue" type="radio" >
      <label id="valobjectlabel" for="valobject">Object</label>
      <br>
      <input id="valarray" name="jsonvalue" type="radio" >
      <label id="valarraylabel" for="valarray">Array</label>
      <br>
      <input id="valplaintext" name="jsonvalue" type="radio">
      <label id="valplaintextlabel" for="valplaintext">Plain text</label>
      <br><textarea id="txt"  rows="5" cols="41"></textarea>
      <br>
      <input id="valnumber" name="jsonvalue" type="radio">
      <label id="valnumberlabel" for="valnumber">Number</label>
      <input id="valnumberinp" name="number" type="number">
      <br>
      <input id="valtrue" name="jsonvalue" type="radio">
      <label id="valtruelabel" for="valtrue">True</label>
      <input id="valfalse" name="jsonvalue" type="radio">
      <label id="valfalselabel" for="valfalse">False</label>
    </td>
  </tr>
  <tr>
      <td colspan="2">
        <select id="dir">
          <!--<option>Пункт 1</option>
          <option>Пункт 2</option>-->
        </select>
        <button id="btn">←  Add in</button></br>        
      </td>
  </tr>
  <tr>
      <td colspan="2" id="result">
        Result:<br>
      </td>
  </tr>
</table>
<span id="result2" ></span>
<span id="list" ></span>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/Larvatus/json-constructor-zRRbrv */
body {
  font-family: Lato;
  background-color: #eaeaea;
  color: #555;
  padding: 10px;
}
#mainTable td {
  padding: 15px;
  background-color: #efefef;
  border: 1px solid #f8f8f8;
}
#keylist, #keynew {
  width: 300px;
}
#keylist, #keynew, #dir, #txt {
  margin:5px 5px 5px 22px;
}
#dir {
  width: 590px;  
}
#template {
  width: 227px;
  margin:0px 5px 0px 15px;
}
#valnumberinp {
  width: 227px;
  margin:0px 5px 0px 15px;
}

/*Downloaded from https://www.codeseek.co/Larvatus/json-constructor-zRRbrv */
var mainArr = {
    "title": "апроапропр пр апр оп ",
    "sections": [
		{
			"title": "апроапр опр ",
			"arabicTitle": "ا",
			"cards": [
				{
					"contentItems": [
						{
							"type": "plainText",
							"content": "апр апр опар о"
						},
						{
							"type": "highlitedText",
							"content": "апр апр оап ро"
						},
						{
							"type": "highlitedText",
							"content": "ап роап роап ро"
						},
						{
							"type": "plainText",
							"content": "ап роапр оап р"
						}
					]
				}
        ]
      
        }
      ]
};

jkey = "jsonkey";
jval = "jsonval";

var keylistItems = ["title","sections", "cards"];
var valuelistItems = ["plainText","highlitedText"];
var dirlistItems = ["/"];

document.getElementById('keylist').onclick = function() {
     document.getElementById('keyfromlist').checked = true;
}
document.getElementById('keyfromlistlabel').onclick = function() {
     document.getElementById('keyfromlist').checked = true;
}
document.getElementById('keynew').onclick = function() {
     document.getElementById('keyfrominput').checked = true;
}
document.getElementById('keyfrominputlabel').onclick = function() {
     document.getElementById('keyfrominput').checked = true;
} 
document.getElementById('valtemplatelabel').onclick = function() {
     document.getElementById('valtemplate').checked = true;
}
document.getElementById('template').onclick = function() {
     document.getElementById('valtemplate').checked = true;
}
document.getElementById('valobjectlabel').onclick = function() {
     document.getElementById('valobject').checked = true;
}
document.getElementById('valarraylabel').onclick = function() {
     document.getElementById('valarray').checked = true;
}
document.getElementById('valplaintextlabel').onclick = function() {
     document.getElementById('valplaintext').checked = true;
}
document.getElementById('txt').onclick = function() {
     document.getElementById('valplaintext').checked = true;
}
document.getElementById('valnumberlabel').onclick = function() {
     document.getElementById('valnumber').checked = true;
}
document.getElementById('valnumberinp').onclick = function() {
     document.getElementById('valnumber').checked = true;
}
document.getElementById('valtruelabel').onclick = function() {
     document.getElementById('valtrue').checked = true;
}
document.getElementById('valfalselabel').onclick = function() {
     document.getElementById('valfalse').checked = true;
}
document.getElementById("btn").onclick = addPair;

//var selectlinks = getArrElType(mainArr);
//selectlinks.unshift('/');

//filldir(selectlinks);
//defineUI(selectlinks);
defineUI();

function defineUI() {
  document.getElementById("template").innerHTML = "";
  valuelistItems.forEach(function(item, i, arr){
    document.getElementById("template").innerHTML += '<option name="jvlistitem" value="'+ item+'">'+ item +'</option>';
  });
  
  //dirlistItems = selectlinks || '';
  dirlistItems = getArrElType(mainArr);
  dirlistItems.unshift("/");
  document.getElementById("keylist").innerHTML = "";
  keylistItems.forEach(function(item, i, arr){
    document.getElementById("keylist").innerHTML += '<option name="jklistitem" value="'+ item+'">'+ item +'</option>';
  });
  
  document.getElementById("dir").innerHTML = "";
  dirlistItems.forEach(function(item, i, arr){
    document.getElementById("dir").innerHTML += '<option name="dirlistitem" value="'+ item+'">'+ item +'</option>';
    
  });
}



function addPair(){
  if (document.getElementById('keyfromlist').checked) {
    var e = document.getElementById("keylist");
    jkey = e.options[e.selectedIndex].value;
  } else {
    jkey = $("#keynew").val();
    if (jQuery.inArray( jkey, keylistItems) == -1) {
      keylistItems.push(jkey);
    }
    
  }

  if (document.getElementById('valtemplate').checked) {
    var ev = document.getElementById("template");
    jval = ev.options[ev.selectedIndex].value;
  }
  if (document.getElementById('valplaintext').checked) {
    jval = $("#txt").val();
  }
  if (document.getElementById('valobject').checked) {
    jval = {};
  }
  if (document.getElementById('valarray').checked) {
    jval = [];
  }
  if (document.getElementById('valnumber').checked) {
    jval = Number($("#valnumberinp").val());
  }
  if (document.getElementById('valtrue').checked) {
    jval = true;
  }
  if (document.getElementById('valfalse').checked) {
    jval = false;
  }
  
  var edir = document.getElementById("dir");
  //edir.options[edir.selectedIndex].value;
  if (edir.options[edir.selectedIndex].value != "/") {
    //alert(edir.options[edir.selectedIndex].value);
   //var tempmainArr = getsubObjFromLink(mainArr, edir.options[edir.selectedIndex].value);
    //mainArr[jkey] = jval;
    addNew(mainArr, edir.options[edir.selectedIndex].value, jkey, jval);
    
  } else {//alert("root");
    mainArr[jkey] = jval;
  }
  

  document.getElementById("result").innerHTML = (JSON.stringify(mainArr, "", 4));
  //var selectlinks = getArrElType(mainArr); 
  //selectlinks.unshift('/');
  
  //addNew(mainArr, edir.options[edir.selectedIndex].value, jkey, jval);
  
  defineUI();
  
}



function getArrElType(obj, parent, links) {
  links = links || [];
  parent = parent || '';
  for (key in obj) {
    if (typeof obj[key] == "object") {
      //document.getElementById("result").innerHTML += "<br>" + parent + "/" + key;
      var linksKey = parent + "/" + key;
      links.push(linksKey);
      var newParent = parent + "/" + key;
      getArrElType(obj[key], newParent, links);
      //document.getElementById("result").innerHTML += "<br>" + parent + "/" + key;
    }
  }
  
  return links;
}


function linksList(arr){
  for (var i=0; i < arr.length; i++) {
    document.getElementById("list").innerHTML += "<br>"+i+". "+arr[i];
  }
}


function getsubObjFromLink(obj, link){
  link = link.substr(1);
  var child = link.split("/");
  
  for (var i=0; i<child.length;i++){
    var neededObj = getSub(obj, child[i]);
    obj = neededObj;
  }
  
  return obj;
}


function getSub(object, childLink) {
  return object[childLink];
}


function addNew (obj, link, key, value) {
  console.log(obj);
  link = link.substr(1);
  var child = link.split("/");
  var neededObj = obj;
  console.log(neededObj);
  
  for (var i=0; i<child.length;i++){
    neededObj = getSub(neededObj, child[i]);
    console.log(neededObj);
  }
  
  neededObj[key] = value;
  console.log("added");
  console.log(neededObj);
  neededObj.push({"xxxx":"!!!!!!"});
  document.getElementById("list").innerHTML = "<br>"+neededObj;
  console.log(neededObj);
  mainArr = neededObj; 
  document.getElementById("result").innerHTML = (JSON.stringify(mainArr, "", 4));
}

Comments