如何在 PHP 中验证 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7841670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:28:32  来源:igfitidea点击:

How to validate JSON in PHP?

phpjsonwell-formed

提问by Jeff Lambert

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.

有没有办法在不使用的情况下检查变量是否是 PHP 中的有效 JSON 字符串json_last_error()?我没有 PHP 5.3.3。

回答by Jeff Lambert

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

回答by Marc B

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

回答by Jefferson Lima

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 Schemaand validate it using this library.

如果您想检查您的输入是否是有效的 JSON,您可能对验证它是否遵循特定格式(即模式)感兴趣。在这种情况下,您可以使用JSON Schema定义您的架构并使用此对其进行验证。

Example:

例子:

person.json

人.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()

回答by Dimitrios Desyllas

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

此外,您可以查看包含缺失函数实现的http://php.net/manual/en/function.json-last-error-msg.php

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)

(从网站复制粘贴)

回答by Alex Turpin

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

您可以检查来自的值json_decode是否为null。如果是这样,它是无效的。