28

有什么方法可以在不使用 PHP 的情况下检查变量是否为有效的 JSON 字符串json_last_error()?我的 PHP 版本早于 5.3.0。

4

5 回答 5

65
$ob = json_decode($json);
if($ob === null) {
 // $ob is null because the json cannot be decoded
}
于 2011-10-20T20:17:00.533 回答
14
$data = json_decode($json_string);
if (is_null($data)) {
   die("Something dun gone blowed up!");
}
于 2011-10-20T20:17:18.003 回答
9

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

例子:

人.json

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

验证

<?php

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

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

$validator->isValid()
于 2017-11-10T16:48:01.563 回答
3

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

其中之一是:

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';
        }
    }

(从网站复制粘贴)

于 2017-09-27T06:49:08.367 回答
0

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

于 2011-10-20T20:16:45.020 回答