简体   繁体   English

用angular 6中的json模式验证json

[英]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. 这是我第一次在Angular项目中从事json模式验证工作。我需要帮助来验证JSON模式(来自REST API)。 Below is sample json schema(generated online) 以下是示例JSON模式(在线生成)

 {
  "$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 以下是我的示例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? 请让我知道如何在angular6 / javascript / jquery中验证json?

Thanks 谢谢

you can try Ajv 你可以尝试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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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