Validate a JSON and print it formatted

3

Suppose I copy a string in a textarea, for example:

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";

So with JSON.parse(str) I parsed the string in JSON format, but I would like to show the result in a textarea or something similar and formatted -

Also, if you modify something there and it's wrong, that's an error. Something similar to this web: link

My controller:

$scope.toParseJson= function (str) {
   $scope.jsonValue = str;
}

$scope.validateJson= function (str) {
   $scope.errors= JSON.parse(str);
}

My html

<textarea ng-change="toParseJson(str)" ng-model="str"></textarea><br>
{{errors}}<br>
<textarea ng-change="validateJson(str)" ng-model="jsonValue "></textarea>

1- How do I get in the second textarea to appear mending with their tabulations and differentiating?

2- Is there another elegant way to show the errors?

    
asked by sirdaiz 24.01.2018 в 12:58
source

1 answer

5

Validate a JSON

The method JSON.parse () launches a SyntaxError if the syntax is invalid:

let textoJSON = '{ "hello": "world" <<<ERROR>>> "places": ["Africa", "America", "Asia", "Australia"] }',
    objeto;

try {
    objeto = JSON.parse(textoJSON);
    console.log('Sintaxis Correcta');
}
catch (error) {
    if(error instanceof SyntaxError) {
        let mensaje = error.message;
        console.log('ERROR EN LA SINTAXIS:', mensaje);
    } else {
        throw error; // si es otro error, que lo siga lanzando
    }
}


Print a formatted JSON

The JSON.stringify () method converts an object to JSON, and accept a third parameter with the amount of spaces to use in each tab. I printed the result in a container that respects the blank spaces (ex: a <pre> or a <textarea> ).

let textoJSON = '{ "hello": "world", "places": ["Africa", "America", "Asia", "Australia"] }',
    objeto;
    
//Teniendo un objeto...
objeto = JSON.parse(textoJSON);

//Lo convertimos a JSON formateado con 2 espacios
let textoFormateado = JSON.stringify(objeto, undefined, 2);

//Imprimimos
document.write('<pre>' + textoFormateado + '</pre>');
    
answered by 24.01.2018 / 15:25
source