Search This Blog

2024/04/28

Javascript:Validate JSON against schema

As we know when we have given a xml we can can validate it ,if it follows the
format we are looking far using xsd,similarly there is need for validatio of
json, we check given json is valid json by using JSON.parse() method but it
does not let us to check if json confirms to our own format so here is
library called ajv that precisely do that.

Code 1:
const Ajv = require("ajv")
const ajv = new Ajv()

const schema = {
type: "object",
properties: {
foo: {type: "integer"},
bar: {type: "string"}
},
required: ["foo"],
additionalProperties: false
}
const validate = ajv.compile(schema)

const data = {
foo: 1,
bar: "abc",
add:23
}
const valid = validate(data)
if (!valid) {
console.log(validate.errors)
}else{
console.log("Valid JSON")
}

Output:
[
{
instancePath: '',
schemaPath: '#/additionalProperties',
keyword: 'additionalProperties',
params: { additionalProperty: 'add' },
message: 'must NOT have additional properties'
}
]

Here our json string has additional property called add
so our json is not valid wrt our schema.


Same library can parse the json and it can do same work as
JSON.parse & also it can serialize json object into string.

Code 2:

const Ajv = require("ajv/dist/jtd")
const ajv = new Ajv() // options can be passed, e.g. {allErrors: true}

const schema = {
properties: {
foo: {type: "int32"}
},
optionalProperties: {
bar: {type: "string"}
}
}

const serialize = ajv.compileSerializer(schema)

const data = {
foo: 1,
bar: "abc"
}

console.log("Serializer:",serialize(data))

const parse = ajv.compileParser(schema)

const json = '{"foo": 1, "bar": "abc"}'
const invalidJson = '{"unknown": "abc"}'

parseAndLog(json) // logs {foo: 1, bar: "abc"}
parseAndLog(invalidJson) // logs error and position

function parseAndLog(json) {
const data = parse(json)
if (data === undefined) {
console.log("Parsing Failed:")
console.log(parse.message) // error message from the last parse call
console.log(parse.position) // error position in string
} else {
console.log("Parsing Success:")
console.log(data)
}
}

Output:
Serializer: {"foo":1,"bar":"abc"}
Parsing Success:
{ foo: 1, bar: 'abc' }
Parsing Failed:
property unknown not allowed
11

No comments:

Post a Comment