【问题标题】:How to check if value exists in another properties json schema如何检查值是否存在于另一个属性 json 模式中
【发布时间】:2019-09-21 13:40:02
【问题描述】:

我需要验证该值是否存在于 json 文件的其他属性中,而不是模式文件中。我想知道这是否可能。

我已经搜索了一些关键字,例如“lookup”或“reference”,但结果是对架构文件的引用,而不是 json 数据。

这里是架构

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "title": "List of people cars",
  "properties": {
    "car":{
      "type":"array",
      "items": {
        "properties": {
          "name": {
            "type":"string"
          }
        }
      }
    },
    "people": {
      "type":"array",
      "items":{
        "properties": {
          "fullname":{
            "type":"string"
          },
          "cars":{
            "type":"string"
            // somehow validate if the car exist in car properties
          }
        }
      }
    }
  }
}

这里是json数据

{
  "$schema": "./schema.json",
  "car": [
    {
      "name": "Lamborghini"
    }
  ],
  "people": [
    {
      "fullname": "Ucok",
      "cars": "Lamborghini" //check if the car name exist in the car properties
    }
  ]
}

我希望 people 对象中的汽车属性值是从上面列出的汽车列表中自动完成的

【问题讨论】:

    标签: javascript json jsonschema


    【解决方案1】:

    为了检查一个值是否存在于 javascript 你可以使用 find / findIndex

    let test = {
      "$schema": "./schema.json",
      "car": [
        {
          "name": "Lamborghini"
        }
      ],
      "people": [
        {
          "fullname": "Ucok",
          "cars": "Lamborghini" //check if the car name exist in the car properties
        }
      ]
    };
    
    test.car.find((item) => item.name === 'Lamborghini'); // will return {name: 'Lamborghini'}
    test.car.find((item) => item.name === 'Ferrari'); // will return undefined
    
    test.car.findIndex((item) => item.name === 'Lamborghini'); // will return 0
    test.car.findIndex((item) => item.name === 'Ferrari'); // will return -1
    
    

    如果返回值未定义或 -1 则该值不存在

    【讨论】:

    • 感谢您的回答。但我问的是 json,而不是 javascript。
    • 只是假设因为您标记了 javascript
    猜你喜欢
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 2014-01-02
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多