PHP用の堅牢な(そして防弾の)is_JSON関数スニペットを知っている人はいますか?私は(明らかに)文字列がJSONであるかどうかを知る必要がある状況にあります。
うーん、おそらくJSONLintリクエスト/レスポンスを介して実行しますが、それは少しやり過ぎのようです。
PHP用の堅牢な(そして防弾の)is_JSON関数スニペットを知っている人はいますか?私は(明らかに)文字列がJSONであるかどうかを知る必要がある状況にあります。
うーん、おそらくJSONLintリクエスト/レスポンスを介して実行しますが、それは少しやり過ぎのようです。
組み込みのjson_decode
PHP関数を使用している場合json_last_error
は、最後のエラーを返します(たとえばJSON_ERROR_SYNTAX
、文字列がJSONではなかった場合)。
通常はとにかくjson_decode
戻ります。null
私のプロジェクトでは、この関数を使用しています ( 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エンコードデータではなかった場合にjson_decode
返されるはずのを使用するのはどうですか?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
json_decode()
あなたのための仕事はありませjson_last_error()
んか?「これはJSONのように見えますか」と言う方法、または実際に検証する方法を探していますか?json_decode()
PHP内で効果的に検証する唯一の方法です。
これが最善かつ効率的な方法です
function isJson($string) {
return (json_decode($string) == null) ? false : true;
}
$this->post_data = json_decode( stripslashes( $post_data ) ); if( $this->post_data === NULL ) { die( '{"status":false,"msg":"post_data パラメーターは有効な JSON でなければなりません"}' ); }