23

私の JSON 文字列は次のようにフォーマットされます。

{
    "count":3,
    "data":[
        {
            "a":{"ax":1}
        },
        {
            "b":{"bx":2}
        },
        {
            "c":{"cx":4}
        }
    ]
}

data配列には多くのとaが含まれbていcます。他の種類のオブジェクトはありません。

の場合count==0data空の配列にする必要があります[]

https://github.com/hoxworth/json-schemaを使用して、Ruby でそのような JSON オブジェクトを検証しています。

require 'rubygems'
require 'json-schema'

p JSON::Validator.fully_validate('schema.json',"test.json")

schema.json

{
  "type":"object",
  "$schema": "http://json-schema.org/draft-03/schema",
  "required":true,
  "properties":{
     "count": { "type":"number", "id": "count", "required":true },
     "data": { "type":"array", "id": "data", "required":true,
       "items":[
           { "type":"object", "required":false, "properties":{ "a": { "type":"object", "id": "a", "required":true, "properties":{ "ax": { "type":"number", "id": "ax", "required":true } } } } },
           { "type":"object",  "required":false, "properties":{ "b": { "type":"object", "id": "b", "required":true, "properties":{ "bx": { "type":"number", "id": "bx", "required":true } } } } },
           { "type":"object",  "required":false, "properties":{ "c": { "type":"object", "id": "c", "required":true, "properties":{ "cx": { "type":"number", "id": "cx", "required":true } } } } }
       ]
     }
  }
}

しかし、これtest.jsonは検証に合格しますが、失敗するはずです:

{
  "count":3,
  "data":[
      {
          "a":{"ax":1}
      },
      {
          "b":{"bx":2}
      },
      {
          "c":{"cx":2}
      },
      {
          "c": {"z":"aa"}
      }
   ]
}

そして、これtest.jsonは失敗しますが、合格するはずです:

{
  "count":3,
  "data":[
      {
          "a":{"ax":1}
      },
      {
          "b":{"bx":2}
      }
   ]
}

間違ったスキーマが、data配列にa,b,c1 回含まれていることを検証しているようです。

適切なスキーマとは?

4

1 に答える 1

30

JSON スキーマ仕様のセクション 5.5から。アイテム:

この属性値がスキーマの配列であり、インスタンス
値が配列である場合、インスタンス配列の各位置は、
この配列の対応する位置のスキーマに準拠する必要があります。これ
はタプルタイピングと呼ばれます。

スキーマ定義では、配列の最初の 3 つの要素が正確に 'a'、'b'、および 'c' 要素である必要があります。を空のままitemsにすると、任意の配列要素が許可されます。同様に、additionalItemsが空のままの場合、任意の追加の配列要素が許可されます。

必要なものを取得するには、指定する必要があり"additionalItems": false、 についてはitems、次の (定義から多少短縮されたもの) が機能するはずです。

"items": {
  "type": [
     {"type":"object", "properties": {"a": {"type": "object", "properties": {"ax": { "type":"number"}}}}},
     {"type":"object", "properties": {"b": {"type": "object", "properties": {"bx": { "type":"number"}}}}},
     {"type":"object", "properties": {"c": {"type": "object", "properties": {"cx": { "type":"number"}}}}}
  ]
}
于 2012-05-30T08:03:58.117 に答える