php使用json-schema模塊實現(xiàn)json校驗示例
本文實例講述了php使用json-schema模塊實現(xiàn)json校驗。分享給大家供大家參考,具體如下:
客戶端和服務(wù)端的http信息傳遞,采用json幾乎成了標配。json格式簡單,易于處理,不過由于沒有格式規(guī)定,無法校驗。
好在php有json-schema模塊,可以用來驗證json是否符合規(guī)定的格式。
安裝使用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":{
}
}
}
}
可以在字段里嵌套子結(jié)構(gòu),如果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發(fā)送給客戶端之前校驗是否和約定相同,避免不必要的錯誤。
參考鏈接,json-schema 文檔,php的json-schema 實現(xiàn)。
完整的代碼在此。
PS:本站還提供了如下XML與JSON相關(guān)工具,方便大家參考使用:
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
php代碼在線格式化美化工具:
http://tools.jb51.net/code/phpformat
在線XML格式化/壓縮工具:
http://tools.jb51.net/code/xmlformat
json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
http://tools.jb51.net/code/jsoncodeformat
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP中json格式數(shù)據(jù)操作技巧匯總》、《PHP針對XML文件操作技巧總結(jié)》、《PHP基本語法入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
php實現(xiàn)替換手機號中間數(shù)字為*號及隱藏IP最后幾位的方法
這篇文章主要介紹了php實現(xiàn)替換手機號中間數(shù)字為*號及隱藏IP最后幾位的方法,涉及php字符串替換與正則操作的相關(guān)技巧,需要的朋友可以參考下2016-11-11
PHP中根據(jù)IP地址判斷城市實現(xiàn)城市切換或跳轉(zhuǎn)代碼
先要獲取ip地址相當簡單,下面先介紹兩種獲取IP地址的代碼,后面需要利用QQIP庫來查找當前IP是屬于那個IP段然后得出城市字段并返回2012-09-09
PHP進程通信基礎(chǔ)之信號量與共享內(nèi)存通信
這篇文章主要介紹了PHP進程通信基礎(chǔ)知識中的信號量與共享內(nèi)存通信的相關(guān)資料,有需要的小伙伴可以查看下2017-02-02
php防注入,表單提交值轉(zhuǎn)義的實現(xiàn)詳解
本篇文章是對php防注入,表單提交值轉(zhuǎn)義的實現(xiàn)進行了詳細的分析介紹,需要的朋友參考下2013-06-06

