I am using JSON object as an input in the textfield. Is there any way to validate this JSON object in JavaScript??
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema. To get validation error messages use the IsValid(JToken, JSchema, IList<String> ) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.
Validation of the input JSON message or the message tree is performed against the JSON schema files or OpenAPI definition files that are deployed. JSON schema must be contained in a file with a . json file extension, and it must either contain schema in the name (for example, . schema.
Ajv is used by a large number of JavaScript applications and libraries in all JavaScript environments - Node. js, browser, Electron apps, WeChat mini-apps etc. It allows implementing complex data validation logic via declarative schemas for your JSON data, without writing code.
JSON Validator verifies that your JavaScript Object Notation adheres to the JSON specification: www.json.org. JSON Validator also formats or humanizes your JSON to render it readable following common linting practices such as multi-line and indentation.
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
.
if you wish to validate the object to a certain schema, you could try JSD Validator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With