JSONからYAML Schemaの数値・整数型を定義する

JSON数値がYAML Schemaのintegerとnumber型にどのようにマッピングされるかを学びます。minimum、maximum、multipleOf、exclusiveMinimum、integerとnumberの違いを解説します。

Type Mapping

詳細な説明

YAML Schemaでの数値型マッピング

JSONには単一のnumber型しかありませんが、YAML Schemaはinteger(整数)とnumber(小数を含む任意の数値)を区別します。コンバーターはJSON値から適切な型を推論します。

型推論ルール

JSON値 YAML Schema型
42 integer
3.14 number
0 integer
-17.5 number
1.0 number(小数点あり)

JSON入力の例

{
  "port": 8080,
  "maxConnections": 100,
  "timeout": 30.5,
  "retryFactor": 1.5
}

生成されるYAML Schema

type: object
properties:
  port:
    type: integer
    minimum: 1
    maximum: 65535
  maxConnections:
    type: integer
    minimum: 1
  timeout:
    type: number
    minimum: 0
  retryFactor:
    type: number
    exclusiveMinimum: 0

数値制約

制約 目的
minimum 最小値(包含) minimum: 0
maximum 最大値(包含) maximum: 65535
exclusiveMinimum 最小値(排他) exclusiveMinimum: 0
exclusiveMaximum 最大値(排他) exclusiveMaximum: 100
multipleOf 値が割り切れなければならない multipleOf: 5

ポート番号の検証

ネットワーク設定の一般的なパターン:

port:
  type: integer
  minimum: 1
  maximum: 65535
  description: TCPポート番号

パーセンテージフィールド

cpuThreshold:
  type: number
  minimum: 0
  maximum: 100
  description: CPU使用率のパーセンテージ

ステップ値のmultipleOf

interval:
  type: integer
  minimum: 5
  multipleOf: 5
  description: ポーリング間隔(秒、5の倍数であること)

integerとnumberの選択

値が整数でなければならない場合(カウント、ID、ポート番号)はintegerを使用します。小数精度が必要な場合(パーセンテージ、レート、座標)はnumberを使用します。正しい型を選択することで検証精度が向上します -- ポート番号8080.5type: integerで正しくバリデーションに失敗します。

ユースケース

インフラストラクチャ設定には、1〜65535のポート番号、正の値でなければならないタイムアウト値、整数でなければならないリトライ回数など、厳密な範囲を持つ数値パラメータがよく含まれます。数値制約を持つYAMLスキーマは、サービス障害やリソース枯渇の原因となる設定ミスを防止します。

試してみる — JSON to YAML Schema

フルツールを開く