gpt4 book ai didi

javascript - 在 Angular 6 中使用 json 模式验证 json

转载 作者:行者123 更新时间:2023-11-30 19:28:10 25 4
gpt4 key购买 nike

这是我第一次在 Angular 项目中进行 json 模式验证。我需要帮助来使用 JSON 模式验证 JSON(来自 REST API)。下面是示例 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"
]
}

下面是我的示例 json

{
"specifications": [
{
"templateName": "specifications"
},
{
"services": [
{
"servicename": "name",
"servicedescription": "description"
}
]
},
{
"javaplatform": [
{
"javaversion": "1.8"
}
]
}
]
}

请告诉我如何在 angular6/javascript/jquery 中验证 json?

谢谢

最佳答案

你可以试试Ajv

这里是示例代码

import * as Ajv from 'ajv'


var ajv = new Ajv();
var validate = ajv.compile(schema);
var valid = validate(data);
if (!valid) console.log(validate.errors);

关于javascript - 在 Angular 6 中使用 json 模式验证 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56699081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com