user1059229
user1059229

Reputation: 165

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??

Upvotes: 13

Views: 42533

Answers (5)

Anusha Bhat
Anusha Bhat

Reputation: 431

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;
        }
}

Upvotes: 0

Mark Homans
Mark Homans

Reputation: 757

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

Upvotes: 3

jabclab
jabclab

Reputation: 15042

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.

Upvotes: 28

WarFox
WarFox

Reputation: 4973

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.

Upvotes: 0

Quentin
Quentin

Reputation: 943571

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.

Upvotes: 0

Related Questions