How to validate JSON in PHP?

拟墨画扇 提交于 2019-11-27 17:13:43

问题


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.


回答1:


$ob = json_decode($json);
if($ob === null) {
 // $ob is null because the json cannot be decoded
}



回答2:


$data = json_decode($json_string);
if (is_null($data)) {
   die("Something dun gone blowed up!");
}



回答3:


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

<?php

$data = '{"firstName":"Hermeto","lastName":"Pascoal"}';

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

$validator->isValid()



回答4:


Furthermore you can have a look on http://php.net/manual/en/function.json-last-error-msg.php that contain implementations of the missing function.

One of them is:

if (!function_exists('json_last_error_msg')) {
        function json_last_error_msg() {
            static $ERRORS = array(
                JSON_ERROR_NONE => 'No error',
                JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
                JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
                JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
                JSON_ERROR_SYNTAX => 'Syntax error',
                JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
            );

            $error = json_last_error();
            return isset($ERRORS[$error]) ? $ERRORS[$error] : 'Unknown error';
        }
    }

(Copied pasted from the site)




回答5:


You could check if the value from json_decode is null. If so, it's invalid.



来源:https://stackoverflow.com/questions/7841670/how-to-validate-json-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!