web-dev-qa-db-ja.com

PHPでJSONを検証する方法は?

json_last_error()を使用せずに、変数がPHPの有効なJSON文字列であることを確認する方法はありますか? PHP 5.3.3がありません。

25
user955822
$ob = json_decode($json);
if($ob === null) {
 // $ob is null because the json cannot be decoded
}
54
Jeff Lambert
$data = json_decode($json_string);
if (is_null($data)) {
   die("Something dun gone blowed up!");
}
10
Marc B

入力が有効なJSONであるかどうかを確認する場合は、特定の形式、つまりスキーマに従っているかどうかを検証することもできます。この場合、 JSON Schema を使用してスキーマを定義し、この library を使用してスキーマを検証できます。

例:

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"]
}

検証

<?php

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

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

$validator->isValid()
3
Jefferson Lima

さらに、欠落している関数の実装を含む http://php.net/manual/en/function.json-last-error-msg.php を確認できます。

それらの1つは:

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

(サイトから貼り付けられたコピー)

2

json_decodeの値がnullであるかどうかを確認できます。もしそうなら、それは無効です。

1
Alex Turpin