How can you ensure data integrity when working with JSON decoding in PHP?
When working with JSON decoding in PHP, you can ensure data integrity by validating the JSON data before decoding it. This can be done by using the json_last_error() function to check for any errors in the JSON data before proceeding with decoding. Additionally, you can use the JSON_THROW_ON_ERROR flag when decoding JSON to throw an exception if there are any errors encountered during the decoding process.
$jsonData = '{"key": "value"}';
// Validate JSON data before decoding
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('Invalid JSON data');
}
// Decode JSON data with JSON_THROW_ON_ERROR flag
try {
$decodedData = json_decode($jsonData, true, 512, JSON_THROW_ON_ERROR);
var_dump($decodedData);
} catch (JsonException $e) {
echo 'Error decoding JSON: ' . $e->getMessage();
}