How to validate JSON data in php 8.2 (earlier than PHP 8.3)?
Challenge:
If JSON is valid PHP will return associated array or std object against running json_decode($data) function. But, when receive invalid JSON it won't return associated array or std php object. So, i couldn't retrieve data from received string.
Perplexity suggestion:
1. First option
if ($data === '' || ($decoded = json_decode($data, false)) === null && json_last_error() !== JSON_ERROR_NONE) {
echo "Invalid JSON";
}
2. Second option
try {
$decoded = json_decode($data, false, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo "error messege".$e->getMessage();
}
3. Third option
function isValidJson(string $data): bool {
json_decode($data);
return json_last_error() === JSON_ERROR_NONE;
}
These three option not worked. Means first option not returned "Invalid JSON"and second option not throw error.like that third option also not return false. After few time, i realized if json is invalid json_decode($JSON); functionreturn only string so i just check what is the return value data type and responded client to invalid json (4XX) error.
Comments
Post a Comment