Validating a JSON string with the json_validate PHP function
Published on 2024-08-21 • Modified on 2024-08-21
This snippet shows how to validate a JSON string with the json_validate()
PHP function. This function was introduced in PHP 8.3 and finally allows developers to avoid calling the json_decode()
function twice.
<?php
declare(strict_types=1);
namespace App\Controller\Snippet;
/**
* I am using a PHP trait to isolate each snippet in a file.
* This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
* or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
* Services are injected in the main controller constructor.
*/
trait Snippet315Trait
{
public function snippet315(): void
{
$strings = [
'{foo: bar}', // invalid: key and value not quoted
'{"foo": "bar"}',
];
foreach ($strings as $string) {
echo $string.' '.(json_validate($string) ? '✅' : '❌').PHP_EOL;
}
// That's it! 😁
}
}
Run this snippet More on Stackoverflow Read the doc Random snippet