json prettyPrint method

by fiddlerintheoffice

HTML

<pre id="mid">

</pre>

JavaScript

let json = '{"a": "b", "c": "d", "e": {"f": "g", "h": "i"}, "k": {"l": "m", "n": {"o": "p", "q": "r"}}, "s": [1,2,3,4,5]}';
// detect opening brackets
json = json.replace(/: ?(\{|\[)/g, ':yxy$1');

json = json.replace(/ ?(\}|\])/g, 'yxy$1');
json = json.replace(/([\}\{\]\[,]) ?/g, '$1yxy');
//json = json.replace(/(yxy)+/g, 'yxy');
arrJson = json.split('yxy');
var counter = 0;

function indent(i) {
	var t = '';
  for (var j = 0; j < i; j++) {
  	t += '    ';
  }
  return t;
}

for (var i = 0; i < arrJson.length; i++) {
	var newVal = indent(counter) + arrJson[i];
  if (arrJson[i] === '{' || arrJson[i] === '[') {
        counter++;
  
  }
	if (arrJson[i].match(/\}/) || arrJson[i].match(/\]/)) {
			counter--;  
			newVal = indent(counter) + arrJson[i];
  }
  arrJson[i] = newVal;
  
}
console.log(arrJson)
document.querySelector('#mid').innerHTML = arrJson.join('\n');