当前位置:首页 > PHP教程 > php应用 > 列表

php使用json-schema模块实现json校验示例

发布:smiling 来源: PHP粉丝网  添加日期:2021-12-24 09:48:40 浏览: 评论:0 

本文实例讲述了php使用json-schema模块实现json校验,分享给大家供大家参考,具体如下:

客户端和服务端的http信息传递,采用json几乎成了标配,json格式简单,易于处理,不过由于没有格式规定,无法校验。

好在php有json-schema模块,可以用来验证json是否符合规定的格式。

安装使用composer

composer require justinrainbow/json-schema:~1.3

新建一个schema文件,如:schema.json

  1. { 
  2.   "type": "object", 
  3.   "properties": { 
  4.     "firstName": { 
  5.       "type": "string", 
  6.              "required": true 
  7.     }, 
  8.     "lastName": { 
  9.       "type": "string" 
  10.     }, 
  11.     "age": { 
  12.         
  13.       "type": "integer", 
  14.       "minimum": 0 
  15.     }, 
  16.     "data":{ 
  17.        "type":"object", 
  18.        "required":true, 
  19.        "properties":{ 
  20.         } 
  21.     } 
  22.   } 
  23. } 

可以在字段里嵌套子结构,如果properties为空,则可以任意,比如上例的data。

类型有:

  1. array 
  2. A JSON array. 
  3. boolean 
  4. A JSON boolean. 
  5. integer 
  6. A JSON number without a fraction or exponent part. 
  7. number 
  8. Any JSON number. Number includes integer. 
  9. null 
  10. The JSON null value. 
  11. object 
  12. A JSON object. 
  13. string 
  14. A JSON string. 

php代码如下:

  1. $json = '{"firstName":"ban", "lastName":"shan","age":1,"data":{"hobby":"coding"} }'; 
  2. $validator = new JsonSchema\Validator; 
  3. $schema = file_get_contents("schema.json"); 
  4. $validator->check(json_decode($json), json_decode($schema)); 
  5. if ($validator->isValid()) { 
  6.   echo "The supplied JSON validates against the schema.\n"; 
  7. } else { 
  8.   echo "JSON does not validate. Violations:\n"; 
  9.   foreach ($validator->getErrors() as $error) { 
  10.     echo sprintf("[%s] %s\n", $error['property'], $error['message']); 
  11.   } 
  12. } 

这样先定义好通信的schema,在json发送给客户端之前校验是否和约定相同,避免不必要的错误。

Tags: json-schema json校验

分享到: