I am using JSON object as an input in the textfield. Is there any way to validate this JSON object in JavaScript??
-
Are you trying to validate that it's syntactically valid JSON or that it conforms to a certain schema?jabclab– jabclab2011-12-08 13:13:01 +00:00Commented Dec 8, 2011 at 13:13
-
I am just trying to check whether the object entered in textfield is valid JSON.user1059229– user10592292011-12-08 13:17:04 +00:00Commented Dec 8, 2011 at 13:17
-
you can use intval function for example $id=intval($id); echo json_encode($data)rashidkaif1– rashidkaif12012-12-26 12:54:51 +00:00Commented Dec 26, 2012 at 12:54
5 Answers
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.
10 Comments
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.
Comments
Yes, there are quite a few JSON libraries available for your use.
Try these out when using Java:
- Jackson - A High performance JSON processors
- google-gson - Java library by google
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.