JSON Schemaを使ってみる

やること

JSON Schemaで項目間のチェックをする。 例えば、field1が1の場合に、field2はAであることをチェックする。 JSON Schemaで表現すると以下のようになる。

{
  "type": "object",
  "properties": {
    "field1": {
      "type": "string"
    },
    "field2": {
      "type": "string"
    }
  },
  "if": {
    "properties": {
      "field1": {
        "const": "1"
      }
    }
  },
  "then": {
    "properties": {
      "field2": {
        "const": "A"
      }
    }
  }
}

試した結果

  • Ruby Gem
    • json-schema (2.8.0)
      • "if"はdraft-07からだが、draft-04(実はdraft-06まで?)の実装であり、ifは使えない。
    • json_schemer (0.1.5)
      • 期待通り動作せず。
  • https://www.jsonschemavalidator.net
    • 期待通り。