What are the potential security risks associated with using json_encode in PHP, and how can they be mitigated?

One potential security risk associated with using json_encode in PHP is the possibility of XSS (Cross-Site Scripting) attacks if the input data is not properly sanitized. To mitigate this risk, it is important to ensure that any user input being passed to json_encode is properly sanitized and validated before encoding it.

// Example of sanitizing user input before using json_encode
$user_input = $_POST['user_input'];

// Sanitize user input
$sanitized_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');

// Encode sanitized input
$json_data = json_encode($sanitized_input);