JSON Formatter
Simple JSON pretty-printer, implemented using AngularJS
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);
}
}
}]);