Reputation: 193
This is the first time i m working on json schema validation in Angular project.I need help to validate JSON(from REST API) with JSON schema. Below is sample json schema(generated online)
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"specifications": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"templateName": {
"type": "string"
}
},
"required": [
"templateName"
]
},
{
"type": "object",
"properties": {
"services": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"servicename": {
"type": "string"
},
"servicedescription": {
"type": "string"
}
},
"required": [
"servicename",
"servicedescription"
]
}
]
}
},
"required": [
"services"
]
},
{
"type": "object",
"properties": {
"javaplatform": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"javaversion": {
"type": "string"
}
},
"required": [
"javaversion"
]
}
]
}
},
"required": [
"javaplatform"
]
}
]
}
},
"required": [
"specifications"
]
}
Below is my sample json
{
"specifications": [
{
"templateName": "specifications"
},
{
"services": [
{
"servicename": "name",
"servicedescription": "description"
}
]
},
{
"javaplatform": [
{
"javaversion": "1.8"
}
]
}
]
}
Kindly let me know how to validate json in angular6/javascript/jquery?
Thanks
Upvotes: 4
Views: 6092
Reputation: 1687
you can try Ajv
here is example code
import * as Ajv from 'ajv'
var ajv = new Ajv();
var validate = ajv.compile(schema);
var valid = validate(data);
if (!valid) console.log(validate.errors);
Upvotes: 4