php的json校验json-schema

客户端和服务端的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实现。

 完整的代码在此

 

 
posted @   半山th  阅读(3554)  评论(0)    收藏  举报
编辑推荐:
· 2025年:是时候重新认识System.Text.Json了
· 源码浅析:SpringBoot main方法结束为什么程序不停止
· C#性能优化:为何 x * Math.Sqrt(x) 远胜 Math.Pow(x, 1.5)
· 本可避免的P1事故:Nginx变更导致网关请求均响应400
· 还在手写JSON调教大模型?.NET 9有新玩法
阅读排行:
· 2025年:是时候重新认识System.Text.Json了
· .NET 9 的免费午餐:GZip 性能提升38.3%
· 开源新旗舰 GLM-4.5:不想刷榜,只想干活儿
· 优雅的.net REST API之FastEndpoints
· .NET 10 中的新增功能系列文章1——运行时中的新增功能
点击右上角即可分享
微信分享提示