JSON Object validation in Javascript

I am using JSON object as an input in the textfield. Is there any way to validate this JSON object in javascript??

Answers:

Answer

Building on the idea of @Quentin, you can just do something like:

function isValidJson(json) {
    try {
        JSON.parse(json);
        return true;
    } catch (e) {
        return false;
    }
}

console.log(isValidJson("{}")); // true
console.log(isValidJson("abc")); // false

This will require json2.js to be deployed in the page in order to ensure cross-browser support for the JSON Object.

Answer

if you wish to validate the object to a certain schema, you could try JSD Validator

Answer

Run it through a JSON parser (json2.js if you aren't using a library with one built in) and see if you get data back.

Answer

Yes, there are quite a few JSON libraries available for your use.

Try these out when using Java:

Or if you prefer simple JavaScript, you can go with

David Walsh has given a full example of how to do this in javascript using Mootools, JSON Schema, in the following blog http://davidwalsh.name/json-validation. Give it a go.

Answer

Here is the code that worked for me,

$scope.jsonFunc = function(json){
        try {
            $scope.jsonData = JSON.stringify(JSON.parse(json), null, 2);
            return true;
            $scope.errorMessage = "Valid JSON";
        } catch (e) {
            $scope.errorMessage = e.message;
            return false;
        }
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.