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

2022-04-15 0 1,220

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

客户端和服务端的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发送给客户端之前校验是否和约定相同,避免不必要的错误。

参考链接,json-schema 文档,php的json-schema 实现。

完整的代码在此

PS:本站还提供了如下XML与JSON相关工具,方便大家参考使用:

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

php代码在线格式化美化工具:
http://tools.jb51.net/code/phpformat

在线XML格式化/压缩工具:
http://tools.jb51.net/code/xmlformat

json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat

更多关于PHP相关内容感兴趣的读者可查看本站专题

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 PHP编程 php使用json-schema模块实现json校验示例 https://www.niceym.com/12727.html