What are some common pitfalls when using json_decode in PHP and how can they be avoided?

One common pitfall when using json_decode in PHP is not checking for errors during decoding, which can lead to unexpected behavior or errors in your application. To avoid this, always check the return value of json_decode and handle any errors appropriately.

$json = '{"key": "value"}';
$data = json_decode($json);

if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
    throw new Exception('Error decoding JSON: ' . json_last_error_msg());
}

// continue processing the decoded data