<?php
/**
* Safely decode a JSON string, handling potential errors gracefully.
*
* @param string $jsonString The JSON string to decode.
* @return mixed The decoded JSON object, or null on failure.
*/
function safeJsonDecode(string $jsonString)
{
try {
// Attempt to decode the JSON string.
$jsonObject = json_decode($jsonString, true); // Use true for associative arrays
return $jsonObject;
} catch (JsonException $e) {
// Handle JSON decoding errors.
error_log("JSON decoding error: " . $e->getMessage()); // Log the error
return null; // Return null on failure.
}
}
// Example Usage (for testing):
/*
$json = '{"name": "John", "age": 30}';
$data = safeJsonDecode($json);
if ($data !== null) {
print_r($data);
} else {
echo "Failed to decode JSON.\n";
}
$invalidJson = '{"name": "John", "age": 30'; //missing closing brace
$data = safeJsonDecode($invalidJson);
if ($data !== null) {
print_r($data);
} else {
echo "Failed to decode JSON.\n";
}
*/
?>
Add your comment