2016-09-22 63 views
0

我有這個架構的JSON響應JSON模式爲對象的數組不驗證

{ 
    "title": "Products", 
    "description": "schema for products", 
    "type": "array", 
    "properties": { 
     "id": { 
      "description": "id of a product", 
      "type": "integer" 
     }, 
     "name": { 
      "description": "name of the product", 
      "type": "string" 
     }, 
     "created_at": { 
      "description": "record created_at", 
      "type": "string", 
      "format": "date-time" 
     }, 
     "updated_at": { 
      "description": "record updated_at", 
      "type": "string", 
      "format": "date-time" 
     } 
    }, 
    "required": ["id", "name"] 
} 

,我想這個模式與此JSON

[{ 
    "id": 1, 
    "name": "Cricket Ball" 
}, { 
    "id": 2, 
    "name": "Soccer Ball" 
}, { 
    "id": 3, 
    "name": "football ball" 
}, { 
    "id": 4, 
    "name": "Basketball ball" 
}, { 
    "id": 5, 
    "name": "Table Tennis ball" 
}, { 
    "id": 6, 
    "name": "Tennis ball" 
}] 

匹配這個模式的響應相匹配但它也匹配所需字段是這樣的架構

"required": ["ids", "names"] 

我認爲架構已驗證獲得數組並且數組中的對象未經驗證。

+2

它很不清楚您實際上在做什麼。如果您使用的是AMS,請包含控制器和視圖(如果您使用的是jbuilder)或序列化程序。 – max

+0

這與軌道無關。在最近的編輯中刪除了rails標籤 – Officer

回答

0

你有它成立現在的樣子,你properties鍵指向數組本身,而不是對每個項目,被忽略(因爲數組沒有的特性,它們只是有物品)。您需要使用items密鑰來驗證陣列中的每個項目,如下所示:

{ 
    "title": "Products", 
    "description": "schema for products", 
    "type": "array", 
    "items": { 
     "type": "object", 
     "properties": { 
     "id": { 
      "description": "id of a product", 
      "type": "integer" 
     }, 
     "name": { 
      "description": "name of the product", 
      "type": "string" 
     }, 
     "created_at": { 
      "description": "record created_at", 
      "type": "string", 
      "format": "date-time" 
     }, 
     "updated_at": { 
      "description": "record updated_at", 
      "type": "string", 
      "format": "date-time" 
     } 
     }, 
     "required": ["id", "name"] 
    } 
} 
+0

PS [json scheme validator](http://www.jsonschemavalidator.net)是一種很好的方式來測試現場模式。 – omnikron

+0

它做到了。真棒 – Officer

0

嘗試map

new_array = response.map{ |k| { 'id': k['properties']['id']['description'], 'name': k['properties']['name']['description'] } } 
+0

對不起,但這並不是我所要求的。我不希望第一個轉換爲第二個。我想要匹配[json-schema](http://json-schema.org/) – Officer