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

本文实例讲述了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发送给客户端之前校验是否和约定相同,避免不必要的错误。

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

完整的代码。

ps:本站还提供了如下xml与json相关工具,方便大家参考使用:

在线xml/json互相转换工具:

php代码在线格式化美化工具:

在线xml格式化/压缩工具:

json代码在线格式化/美化/压缩/编辑/转换工具:

希望与广大网友互动??

点此进行留言吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值