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

吾爱主题 阅读:125 2021-08-23 16:34:00 评论:0

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

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

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

安装使用composer

?
1 composer require justinrainbow /json-schema :~1.3

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

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 {    "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代码如下:

?
1 2 3 4 5 6 7 8 9 10 11 12 $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 实现。

完整的代码在此

希望本文所述对大家PHP程序设计有所帮助。

原文链接:https://www.cnblogs.com/xdao/p/json-schema_use_php.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容