What are common pitfalls when handling JSON data in PHP and how can they be avoided?

One common pitfall when handling JSON data in PHP is not properly decoding the JSON string before trying to access its values. This can result in errors or unexpected behavior. To avoid this, always use the `json_decode()` function to convert the JSON string into a PHP object or array before working with the data.

// Example of decoding JSON data properly
$jsonString = '{"name": "John", "age": 30}';
$data = json_decode($jsonString);

// Accessing values safely
if ($data !== null) {
    echo $data->name; // Output: John
    echo $data->age; // Output: 30
} else {
    echo "Failed to decode JSON data";
}