JSFiddle - React, Tailwind, and code Playground

by lchau

HTML

https://jsfiddle.net/#save

JavaScript

//var _ = require('lodash');
// _.memoize
// _.repeat(str, count)
// function prettyPrintJson(str: String, indentSize: Number): String {
_.mixin({
  repeat: function(str, times) {
  	return _.times(times, () => str).join('');
  }
});
function prettyPrintJson(str = '', indentSize = 2) {
  let currentPosition = 0;
  let currentIndentationLevel = 0;

  let prettyStr = '';

  while (currentPosition < str.length) {
    const currentChar = str[currentPosition];

    if (currentChar === '{') {
      prettyStr += currentChar + '\n';

      currentIndentationLevel++;

      prettyStr += createWhitespace(currentIndentationLevel, indentSize);
    } else if (currentChar === '}') {
      prettyStr += '\n';

      currentIndentationLevel--;

      prettyStr += createWhitespace(currentIndentationLevel, indentSize);
      prettyStr += currentChar;
    } else if (currentChar === '[') {
      prettyStr += currentChar + '\n';

      currentIndentationLevel++;

      prettyStr += createWhitespace(currentIndentationLevel, indentSize);
    } else if (currentChar === ']') {
      prettyStr += '\n';

      currentIndentationLevel--;

      prettyStr += createWhitespace(currentIndentationLevel, indentSize);
      prettyStr += currentChar;
    } else if (currentChar === ',') {
      prettyStr += currentChar + '\n';
      prettyStr += createWhitespace(currentIndentationLevel, indentSize);
    } else if (currentChar === ':') {
      prettyStr += ': ';
    } else if (currentChar === ' ') {
    } else {
      prettyStr += currentChar;
    }

    currentPosition++;
  }

  return prettyStr;
}

let createWhitespace = _.memoize((indentationLevel, indentationSize) => {
  return _.repeat(' ', indentationLevel * indentationSize);
});

console.log(prettyPrintJson('{"key": "val", "foo": {"key1": 2, "key1": [1, true, [], 3] }}'));

/*

{
  "key": 7,
  "key2": "str",
  "key3": [
    ...
  ],
  "key4": {
    ...
  }
}

{
  "test": 123
}


*/