JSON::TypeInference 1.0 と JSON::Schema::Generator (trial) をリリースした

JSON::TypeInference 1.0

metacpan.org

だいたい欲しいものは実装したので覚悟を決めるという意味での 1.0 リリース。

これはなにか?

Perl の値 (スカラ値、ハッシュリファレンス、配列リファレンスなど) が JSON のどの型であるかを推論するモジュール。

Perl の値から JSON の型を推論するモジュールを書いた - Sexually Knowing

できること

後述の JSON::Schema::Generator のような使い方を念頭に置いてある、というか、そのために作った。

JSON::Schema::Generator

metacpan.org

与えられたデータから型を推論し、構造を再帰的に辿りながら、JSON Schema の雛形を生成する。

こういう感じでデータを与えると:

my $generator = JSON::Schema::Generator->new;
$generator->learn({
  id   => 1,
  name => 'yuno',
});
$generator->learn({
  id   => 2,
  name => 'miyako',
});
$generator->learn({
  id          => 3,
  name        => 'sae',
  accessories => ['eyeglass'],
});
my $schema = $generator->generate;

こういう雛形が得られる:

{
   "$schema" : "http://json-schema.org/draft-04/schema#",
   "description" : "TODO",
   "properties" : {
      "accessories" : {
         "items" : {
            "example" : "eyeglass",
            "type" : "string"
         },
         "type" : "array"
      },
      "id" : {
         "example" : 1,
         "type" : "number"
      },
      "name" : {
         "example" : "yuno",
         "type" : "string"
      }
   },
   "required" : [
      "id",
      "name"
   ],
   "title" : "TODO",
   "type" : "object"
}

array だったら items.example に代表値を置くとか、けっこうおもてなしできていると思う。

null かもしれない値を "type": ["null", "string"] のようにするのがいいのか、required から外すだけでいいのか、もうちょっとユースケースを見極めたい。