简体   繁体   中英

validating json with json schema in angular 6

This is the first time im 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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM