2013-02-13 74 views
2

我想根據給定的Schema來驗證JSON對象。針對JSON Schema的JSON驗證

JSON數據如下:

{ 
"list": { 
    "places": [ 
     { 
      "name": "Loopsiloo", 
      "foursquareID": "54a6s5D4a6s5d4a6s5D4", 
      "lat": 26.6546845354889, 
      "lon": -99.6846873700158 
     }, 
     { 
      "name": "Loopsiloo", 
      "foursquareID": "54a6s5D4a6s5d4a6s5D4", 
     } 
    ], 
    "title": "Foo Bar", 
    "dateCreated": "2013-01-29T14: 19: 30Z" 
} 

JSON模式如下:

{ 
"type":"object", 
"$schema": "http://json-schema.org/draft-03/schema", 
"required":true, 
"properties":{ 
    "list": { 
     "type":"object", 
     "id": "list", 
     "required":true, 
     "properties":{ 
      "dateCreated": { 
       "type":"string", 
       "id": "dateCreated", 
       "required":true 
      }, 
      "places": { 
       "type":"array", 
       "minitems": "1", 
       "id": "places", 
       "required":true, 
       "items": 
       { 
        "type":"object", 
        "required":true, 
        "properties":{ 
         "note": { 
          "type":"string", 
          "id": "note", 
          "required":false 
         }, 
         "foursquareID": { 
          "type":"string", 
          "id": "foursquareID", 
          "required":true 
         }, 
         "lat": { 
          "type":"number", 
          "id": "lat", 
          "required":true 
         }, 
         "lon": { 
          "type":"number", 
          "id": "lon", 
          "required":true 
         }, 
         "name": { 
          "type":"string", 
          "id": "name", 
          "required":true 
         } 
        } 
       } 


      }, 
      "title": { 
       "type":"string", 
       "id": "title", 
       "required":true 
      } 
     } 
    } 
} 

}

我驗證在PHP中使用JsonSchema \驗證這個JSON。

$validator = new JsonSchema\Validator; 
$validator->check($data, file_get_contents(__DIR__ . '/../model/api-schema.json')); 

我的問題是驗證器每次都驗證JSON對象是正確的。在頂部的示例中,缺少屬性「lat」和「lon」。即使我省略了整個「地點」,「標題」或「日期創建」屬性,它也被驗證爲正確。

有什麼我失蹤了嗎?我瀏覽了JSON模式的文檔,但沒有任何東西可以幫助我。

+1

您的驗證庫使用哪個版本的模式標準?在v4中,'required'現在是一個數組而不是布爾值。 – cloudfeet 2013-07-18 12:42:54

+0

有沒有人知道PHP的一個很好的schema4驗證器。沒有什麼似乎正常工作。 – chris 2017-08-31 09:41:07

回答

1

這是對我有用的東西。

$validator = new JsonSchema\Validator; 
$schema = file_get_contents(__DIR__ . '/../model/api-schema.json'); 
$validator->check(json_decode($data), json_decode($schema));