LoginSignup
254
249

More than 5 years have passed since last update.

JSONスキーマはじめの一歩

Last updated at Posted at 2015-04-15

JSONスキーマと、RubyでJSONスキーマつかってvalidationするやり方を解説します。

全てがJSONになる - ✘╹◡╹✘ を読んでJSON schema良さ気だと思ったけど、まだ使ったことない人向けの記事です。

JSONスキーマって?

本屋のJSONデータを返すAPIがあったとします。

bookshop.json
{
  "name": "おしゃれな本屋",
  "place": {
    "large_area": "おしゃれな地域",
    "small_area": "おしゃれな街",
    "address": "おしゃれな街のおしゃれな建物",
    "latitude": 33.333,
    "longitude": 33.333
  }
}

これに対して、JSONスキーマを用意しておけば、1つ1つの値の有無や型をチェックできます。生成したJSONが意図したものになっているかテストするのに便利です。

JSONスキーマといいつつJSONだと括弧が多くて冗長なので、YAMLで書いてJSONに変換するのがおすすめです。YAMLだとコメント書けますし。

bookshop-schema.yml
---
$schema: "http://json-schema.org/draft-04/schema#"
title: "Bookshop"
type: "object"
required: # 必須のプロパティを定義
  - "name"
  - "place"
properties:
  name:
    type: "string" # "おしゃれな本屋"は文字列
  place:
    type: "object"
    required:
      - "large_area"
      - "small_area"
      - "address"
      - "latitude"
      - "longitude"
    properties:
      large_area:
        type: "string"
      small_area:
        type: "string"
      address:
        type: "string"
      latitude:
        type: "number" # 33.333は数値
      longitude:
        type: "number"
additionalProperties: false

validationはどうやるの?

rubyで説明します。
ruby-json-schema/json-schemaというgemを使います。

validation.rb
require 'json-schema'
require 'yaml'

json = File.open('./bookshop.json').read
schema = JSON.dump( YAML::load( File.open('./bookshop-schema.yml').read ) )
p JSON::Validator.fully_validate(schema, json, :strict => false)

validationで特にエラーがなかった場合、空の配列が出力されます。
エラーがあった場合は、次のように出力されます。

["The property '#/name' of type NilClass did not match the following type: string in schema ecf16823-628c-5899-a01c-4978dcd6883b#", "The property '#/place/address' of type Array did not match the following type: string in schema ecf16823-628c-5899-a01c-4978dcd6883b#"]

サンプルコードを上げておいたので、詳しくはこちらを。
sagaraya/json-schema-sample

JSONスキーマについて補足

$schemaって?

JSONスキーマの仕様はいくつかのバージョンがあるため、どのバージョンを使うか宣言します。最新はdraft-04です。

詳しくは The $schema keyword — Understanding JSON Schema 1.0 documentation へ。

どんなキーワードや型が使えるの?

英語ですが、JSON Schema Reference — Understanding JSON Schema 1.0 documentation が一番よくまとまってます!

型については Type-specific keywords にまとまっていて、それ以外のページにどのようなキーワードが使えるか載ってます。

応用

今回はAPIのレスポンスを例に挙げましたが、リクエストパラメータのvalidationにも使えます。また、JSONスキーマからドキュメントを自動生成したり、APIクライアントを自動生成したりできます。JSONスキーマ1つで色々なことができるようになって便利!

254
249
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
254
249