Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 587
user1059229 Avatar asked Dec 08 '11 13:12

user1059229


People also ask

How do I check if a JSON is valid?

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.

What is JSON input validation?

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.

What is the use of Ajv?

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.

What are JSON validators?

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.


2 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.

like image 82
jabclab Avatar answered Sep 25 '22 03:09

jabclab


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

like image 40
Mark Homans Avatar answered Sep 23 '22 03:09

Mark Homans