JSON Formatter
Simple JSON pretty-printer, implemented using AngularJS
by Kristopher Johnson
HTML
<h1>JSON Reformatter</h1>
<form ng-app="formatterApp" ng-controller="formatterController">
<textarea
ng-model="inputText"
id="inputTextarea"
rows="5"
cols="40"
placeholder="Paste your JSON here"
autofocus="true"
></textarea>
<br>
<button ng-click="clearInputText();">Clear Input Text</button>
<br>
<textarea
ng-bind="outputText"
ng-class="outputClass"
rows="5"
cols="40"
placeholder="Reformatted JSON will appear here"
readonly="true"
></textarea>
<br>
<label>
Indentation:
<select
ng-options="option.label for option in indentOptions"
ng-model="selectedIndentOption">
</select>
</label>
</form>
<p class="small">
For more about this webapp, see <a href="http://undefinedvalue.com/2014/05/28/web-page-reformatting-json-text-using-angularjs">A Web Page for Reformatting JSON Text, using AngularJS</a>
</p>
CSS
body {
font-family: sans-serif;
}
textarea {
border: 1px solid black;
font-family: monospace;
font-size: 10pt;
}
.small {
font-size: smaller;
}
.output-good {
color: green;
background-color: white;
}
.output-error {
color: white;
background-color: red;
}
JavaScript
angular.module('formatterApp', [])
.controller('formatterController', ['$scope', '$window', function($scope, $window) {
$scope.inputText = '';
$scope.indentOptions = [
{label: 'None', value: 0 },
{label: 'One Space', value: 1 },
{label: 'Two Spaces', value: 2 },
{label: 'Three Spaces', value: 3 },
{label: 'Four Spaces', value: 4 },
{label: 'Eight Spaces', value: 8 },
{label: 'Tab', value: '\t'}
];
$scope.selectedIndentOption = $scope.indentOptions[2];
$scope.clearInputText = function() {
$scope.inputText = '';
$window.document.getElementById('inputTextarea').focus();
};
$scope.$watch('inputText', updateOutput);
$scope.$watch('selectedIndentOption', updateOutput);
function updateOutput() {
try {
var indent = $scope.selectedIndentOption.value;
$scope.outputText = formatJSON($scope.inputText, indent);
$scope.outputClass = 'output-good';
}
catch (err) {
$scope.outputText = err.message;
$scope.outputClass = 'output-error';
}
}
function formatJSON(input, indent) {
if (input.length == 0) {
return '';
}
else {
var parsedData = JSON.parse(input);
return JSON.stringify(parsedData, null, indent);
}
}
}]);