json-schema-php:JSON 結構驗證 PHP 實現
JSON Schema 用于描述JSON數據的結構和類型。如同DTD與XML的關系。
本實現用于使用 PHP 調用 JSON Schema 對 JSON 數據進行驗證。
包括 PHP 和 PHP擴展 ,建議PHP版本 PHP 5 >= 5.2.0、PECL json >= 1.2.0。
生成 JSON Schema
由JSON生成一個全格式的Schema,方便編輯修改(勿隨便直接使用在實踐中)。
$value = new stdClass(); $value->name = 'a name'; $value->age = 23; $value->height = 183.5; $jsonSchema = new JsonSchema(json_encode($value)); echo $jsonSchema->getSchema();
結果(真實結果格式化后)
{
"type":"object",
"properties":{
"name":{
"type":"string",
"format":"regex",
"pattern":"\/^[a-z0-9]+$\/i",
"minLength":0,
"maxLength":2147483647
},
"age":{
"type":"integer",
"default":0,
"minimum":0,
"maximum":2147483647,
"exclusiveMinimum":0,
"exclusiveMaximum":2147483647
},
"height":{
"type":"number",
"default":0,
"minimum":0,
"maximum":2147483647,
"exclusiveMinimum":0,
"exclusiveMaximum":2147483647
}
}
}
使用 JSON Schema 驗證 JSON
$userType = '
{
"id": "user",
"description": "user info",
"type": "object",
"properties": {
"account": {"type": "string"},
"email": {"type": "string", "required": true},
"noexist": {"type": "string", "required": false}
}
}';
$type = array();
$type['users'][] = array('account' => 'userA', 'email' => 'userA@example.com');
$type['users'][] = array('account' => 'userB', 'email' => 'userB@example.com');
$type['users'][] = array('account' => 'userC', 'email' => 'userC@example.com');
$jsonSchema = new JsonSchema(json_encode($type));
$jsonSchema->addTypes($userType);
$jsonSchema->validate('
{
"type":"object",
"properties":{
"users":{
"type":"array",
"items":{
"$ref":"user"
}
}
}
}'); 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!