使用 Json Schema 和 AJV 验证数组中的唯一属性

问题描述 投票:0回答:1

这是示例数据:-

"labels": [
            {"name" : "sampleId", "value" : "12345"}, 
            {"name" : "SAMPLEID", "value" : "12345"}
          ]

我希望 name 在这个数组中是唯一的,我使用 2007 草案作为 json 模式,它没有为此类用例指定任何标准关键字。我能够使用 ajv-keywords,因为它有一个关键字 uniqueItemProperties,它在某种程度上解决了问题,唯一的问题是它不区分大小写匹配,而根据我的用例,name 应该允许不同的情况,是有没有办法在不编写自定义验证器的情况下解决这个问题?

javascript node.js jsonschema json-schema-validator ajv
1个回答
0
投票

您可以使用

uniqueItems: true
。此关键字验证比较两个对象实例的深度相等性。外壳将被保留并被认为是独一无二的。

{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
    "labels": {
        "type": "array",
        "uniqueItems": true,
        "items": {
             "type": "object",
             "properties": {
                  "name": {
                     "type": "string"
                  },
                  "value": {
                     "type": "string"
                  }
             }
         }
     }
  }
}
const Ajv = require('ajv')
const better = require('better-ajv-errors').default
let _ajvOptions = {
    strict: false,
    allErrors: true,
    messages: true
};
const mySchema = require('./mySchema.json')

const data = {
    "labels": [
        { "name": "sampleId", "value": "12345" },
        { "name": "SAMPLEID", "value": "12345" }
    ]
}


const schema = {
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properites": {
        "labels": {
            "type": "array",
            "uniqueItems": true,
            "items": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string"
                    },
                    "value": {
                        "type": "string"
                    }
                }
            }
        }
    }
}

try {
    let ajv = new Ajv(_ajvOptions);
    ajv.addSchema(mySchema, "https://www.test.com/")

    let validate = ajv.compile(schema)


    let results = validate(data)
    console.log(results = {
        valid: results,
        error: better(schema, badData, validate.errors, { format: "js", indent: 4 })
    })
} catch (err) {
    console.error(results = {
        valid: false,
        error: err.message,
    })

}

© www.soinside.com 2019 - 2024. All rights reserved.