node.js - JSON Schema/AJV 数组项必须位于另一个数组中

标签 node.js jsonschema ajv

我正在使用 Node 的 AJV(它强制执行 JSON 架构)。

我想验证 array1 properties.bars。很简单。

然后我想确保 array2 properties.keep 中的项目位于 array1 properties.bars 中。

我该怎么做?

我有:

const config = require('../../../config')
const VALID_BARS = Object.keys(config.LHS_RHS_LOOKUP)

const schemaItems = {
  id: 'schemaItems',
  type: 'string',
  anyOf: [
    { enum: VALID_BARS },
    { pattern: '^[^\\s]+ [^\\s]+$' }
  ]
}

const schemaOptions = {
  type: 'object',
  properties: {
    bars: {
      type: 'array',
      default: [VALID_BARS[0]],
      items: schemaItems,
      minItems: 1,
      uniqueItems: true
    },
    keep: {
      type: 'array',
      default: [],
      items: schemaItems, // << THIS NEEDS TO CHANGE
      minItems: 0,
      uniqueItems: true
    },
    protect: {
      default: true,
      type: 'boolean'
    }
  }
}

module.exports = schemaOptions

最佳答案

您可能想要使用$data pointer到第一个数组。现在它只是一个 proposal 。它允许您使用另一个属性的数据值向关键字分配值。

因此,在这种情况下,第二个数组的 items 属性将具有一个枚举属性,该属性将使用第一个数组的 $data 值。

为了做到这一点,我必须删除原始架构中的“anyOf”,以便第一个数组最终不会引用自身。我还通过 $ref 和定义将 schemaItems 组合到主架构中。

这是a PLNKR它在行动中。

测试代码如下所示:

let schema = {
  definitions: {
    schemaItems: {
      id: 'schemaItems',
      type: 'string',
      pattern: '^[^\\s]+ [^\\s]+$'
    }
  },
  type: 'object',
  properties: {
    bars: {
      type: 'array',
      items: {
        $ref: "#/definitions/schemaItems"
      },
      minItems: 1,
      uniqueItems: true
    },
    keep: {
      type: 'array',
      items: {
        type: 'string',
        enum: {
          "$data": "/bars"
        }
      },
      minItems: 0,
      uniqueItems: true
    },
    protect: {
      default: true,
      type: 'boolean'
    }
  }
};

有效的数据样本是:

let data = {
  bars: [
    "d d",
    "b b"
  ],
  keep: [
    "d d"
  ],
  protect: true
};

关于node.js - JSON Schema/AJV 数组项必须位于另一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46715231/

相关文章:

javascript - 如何设置自定义 AJV 关键字?

reactjs - 错误 "custom keyword definition is invalid: data.errors should be boolean"

node.js - 当我在 node.js 中使用誓言时出现奇怪的错误

javascript - 通过 Node.js 路由 http 请求

node.js - 语法错误: Unexpected end of JSON input while parsing near '…: {"name":"@babel/plug' ?

mysql - mysql json数据类型的数据搜索问题

node.js - 将 cookieSession 与 Passport 一起使用

rest - Slim - 修改中间件内的 POST 请求正文

json - 在JSON模式中,关键字 "extends"是什么意思

javascript - 使用 Dojo 时无法识别外部库 (AJV)