How to validate JSON in PHP?

后端 未结 5 2060
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 16:41

Is there any way to check that a variable is a valid JSON string in PHP without using json_last_error()? I don\'t have PHP 5.3.3.

5条回答
  •  轮回少年
    2020-12-15 17:21

    If you want to check if your input is valid JSON, you might as well be interested in validating whether or not it follows a specific format, i.e a schema. In this case you can define your schema using JSON Schema and validate it using this library.

    Example:

    person.json

    {
        "title": "Person",
        "type": "object",
        "properties": {
            "firstName": {
                "type": "string"
            },
            "lastName": {
                "type": "string"
            },
            "age": {
                "description": "Age in years",
                "type": "integer",
                "minimum": 0
            }
        },
        "required": ["firstName", "lastName"]
    }
    

    Validation

    validate($data, (object)['$ref' => 'file://' . realpath('person.json')]);
    
    $validator->isValid()
    

提交回复
热议问题