What is the purpose of json_encode in PHP and what potential pitfalls can arise when using it?

The purpose of json_encode in PHP is to convert a PHP array or object into a JSON string. One potential pitfall when using json_encode is that it may not handle certain data types or structures correctly, leading to unexpected results. To avoid this, make sure to properly sanitize and validate the data before encoding it.

$data = array("name" => "John", "age" => 30);
$json_string = json_encode($data);
echo $json_string;