Reputation: 165
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
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
Reputation: 757
if you wish to validate the object to a certain schema, you could try JSD Validator
Upvotes: 3
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
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