What are common pitfalls when decoding JSON in PHP, and how can they be avoided?

Common pitfalls when decoding JSON in PHP include not checking if the JSON string is valid before decoding it, not handling errors that may occur during decoding, and not properly sanitizing the input data. To avoid these pitfalls, always validate the JSON string before decoding it, use try-catch blocks to handle decoding errors, and sanitize the input data to prevent security vulnerabilities.

// Check if the JSON string is valid before decoding
$jsonString = '{"key": "value"}';
if (json_decode($jsonString) === null && json_last_error() !== JSON_ERROR_NONE) {
    // Handle invalid JSON string
}

// Use try-catch blocks to handle decoding errors
$jsonString = '{"key": "value"}';
try {
    $decodedData = json_decode($jsonString);
    // Handle decoded data
} catch (Exception $e) {
    // Handle decoding error
}

// Sanitize the input data before decoding
$jsonString = '{"key": "value"}';
$cleanJsonString = filter_var($jsonString, FILTER_SANITIZE_STRING);
$decodedData = json_decode($cleanJsonString);