かどうかを判断する方法について文字列が有効なJSON?
-
19-09-2019 - |
質問
なんだろうけど、日本人の評価および防弾)is_JSON機能のスニペットのためのPHP?いろいがい知る必要がある場合は文字列をJSONです。
Hmmも行なコストダウンが期待でき JSONLint 要求/応答が得られるように見えるビットを失わせないアイテムです。
解決
ご利用の場合は内蔵 json_decode
PHP関数 json_last_error
を返します最後のエラーの例 JSON_ERROR_SYNTAX
が文字列なJSON).
通常 json_decode
を返します null
ます。
他のヒント
どの程度使用して json_decode
に、与えられた文字列が有効なJSONエンコードされたデータでなかった場合null
を返すべき?
のマニュアルページの例3を参照してください。
// the following strings are valid JavaScript but not valid JSON
// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null
// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null
// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null
は、私のプロジェクトのために私は<のhref = "http://php.net/manual/en/function.json-decode.phpに "の注" をお読みください(この機能を使用します#refsect1-function.jsonデコードパラメータ」REL = "noreferrer"> json_decode()のドキュメント)。
あなたが特定のアプリケーション「エラー」を検出することができます)(json_decodeに渡すのと同じ引数を渡す(例えば深エラー)
PHPで> = 5.6
// PHP >= 5.6
function is_JSON(...$args) {
json_decode(...$args);
return (json_last_error()===JSON_ERROR_NONE);
}
PHPで> = 5.3
// PHP >= 5.3
function is_JSON() {
call_user_func_array('json_decode',func_get_args());
return (json_last_error()===JSON_ERROR_NONE);
}
使用例:
$mystring = '{"param":"value"}';
if (is_JSON($mystring)) {
echo "Valid JSON string";
} else {
$error = json_last_error_msg();
echo "Not valid JSON string ($error)";
}
あなたのためのjson_decode()
作業をjson_last_error()
ませんか?あなたは「これはJSONのように見えるん」と言うか、実際にそれを検証するだけの方法をお探しですか? json_decode()
が効果的にPHPの中でそれを検証する唯一の方法となります。
$this->post_data = json_decode( stripslashes( $post_data ) ); if( $this->post_data === NULL ) { die( '{"status":false,"msg":"The post_data parameter must be valid JSON"}' ); }
このは最高で効率的な方法である。
function isJson($string) {
return (json_decode($string) == null) ? false : true;
}