Check if the String is JSON String in PHP
The code below checks whether passed string looks like a JSON string. Decodes it if it is a JSON string.
This is an analog of maybe_unserialize(), but only for JSON data.
/** * Decodes JSON string only if specified string is really JSON, * otherwise return original passed data. * * Based on {@see https://stackoverflow.com/questions/6041741} * * @param mixed $data String to check and decode. * @param int $flags json_decode() fourth parameter. {@see https://php.net/json_decode} * * @return mixed JSON data if a JSON string is passed. * Original passed data if it is not a JSON string. */ function maybe_json_decode( $data, $flags = 0 ){ if( ! is_string( $data ) ){ return $data; } $data = trim( $data ); $json = json_decode( $data, null, 512, $flags ); if( json_last_error() !== JSON_ERROR_NONE ){ return $data; } if( $json === $data ){ return $data; } return $json; }
Usage example:
$tests = [ '{ "asd": 123 }', 12, ' 123', '[ 123 ]', '{foo}', ]; foreach( $tests as $data ){ var_dump( maybe_json_decode( $data ) ); } /* object(stdClass)#1301 (1) { ["asd"]=> int(123) } int(12) int(123) array(1) { [0]=> int(123) } string(5) "{foo}" */