0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JSON Schema Draft 7 バリデータをゼロから実装した

0
Posted at

作ったもの

JSON Schema Validatorhttps://sen.ltd/portfolio/json-schema-validator/

スクリーンショット

  • Draft 7 の 25+ キーワードをサポート
  • JSON Pointer 形式のエラーパス表示
  • Format バリデータ(email / uri / date / uuid / ipv4 など)
  • 3 つのサンプルスキーマ(User / Product / Config)
  • リアルタイムバリデーション
  • 日英 UI

vanilla JS、ゼロ依存、ビルド不要node --test で 87 ケース。

再帰バリデータ

スキーマとデータを同時にたどり、エラーにパスを付けて積み上げる:

if (schema.properties) {
  for (const [key, propSchema] of Object.entries(schema.properties)) {
    if (key in data) {
      errors.push(...validate(propSchema, data[key], `${path}/${key}`));
    }
  }
}

path/ で連結していくだけで、深いネスト内のエラーも /user/addresses/0/city のように表示できる。

multipleOf の浮動小数点罠

const r = Math.abs(data / mf - Math.round(data / mf));
if (r > 1e-10) errors.push(...);

0.1 * 3 !== 0.3 なので % 演算では不正解になる。割って丸めて比較するのが正解。

oneOf と anyOf の違い

  • allOf: 全てのサブスキーマを満たす(AND)
  • anyOf: 1 つ以上のサブスキーマを満たす(OR)
  • oneOf: ちょうど 1 つのサブスキーマを満たす(XOR)

多くの場合は anyOf で十分。oneOf を書いている 9 割は本当は anyOf を書きたい。

exclusiveMinimum の 2 仕様

Draft 4: { "minimum": 10, "exclusiveMinimum": true }(真偽値)
Draft 6+: { "exclusiveMinimum": 10 }(数値)

実際のスキーマはどちらも存在するので両方対応しないと古い API スキーマで落ちる。

シリーズ

100+ 公開ポートフォリオ シリーズの #78 です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?