天天看點

json schema php解析,php的json校驗json-schema

用戶端和服務端的http資訊傳遞,采用json幾乎成了标配。json格式簡單,易于處理,不過由于沒有格式規定,無法校驗。

好在php有json-schema子產品,可以用來驗證json是否符合規定的格式。

安裝使用composer

composer require justinrainbow/json-schema:~1.3

建立一個schema檔案,如:schema.json

{

"type": "object",

"properties": {

"firstName": {

"type": "string",

"required": true

},

"lastName": {

"type": "string"

},

"age": {

"type": "integer",

"minimum": 0

},

"data":{

"type":"object",

"required":true,

"properties":{

}

}

}

}

可以在字段裡嵌套子結構,如果properties為空,則可以任意,比如上例的data。

類型有:

array

A JSON array.

boolean

A JSON boolean.

integer

A JSON number without a fraction or exponent part.

number

Any JSON number. Number includes integer.

null

The JSON null value.

object

A JSON object.

string

A JSON string.

php代碼如下:

$json = '{"firstName":"ban", "lastName":"shan","age":1,"data":{"hobby":"coding"} }';

$validator = new JsonSchema\Validator;

$schema = file_get_contents("schema.json");

$validator->check(json_decode($json), json_decode($schema));

if ($validator->isValid()) {

echo "The supplied JSON validates against the schema.\n";

} else {

echo "JSON does not validate. Violations:\n";

foreach ($validator->getErrors() as $error) {

echo sprintf("[%s] %s\n", $error['property'], $error['message']);

}

}

這樣先定義好通信的schema,在json發送給用戶端之前校驗是否和約定相同,避免不必要的錯誤

(責任編輯:最模闆)