(PHP 8 >= 8.3.0)
json_validate — Verifica si una string contiene JSON válido
Devuelve si la string dada es sintácticamente JSON válido.
Si json_validate() devuelve true , json_decode()
decodificará con éxito la string dada utilizando los mismos
depth y flags.
Si json_validate() devuelve false , la causa
puede ser recuperada utilizando json_last_error() y
json_last_error_msg() .
json_validate() utiliza menos memoria que json_decode() si el contenido JSON decodificado no es utilizado, ya que no necesita construir la estructura de array o de objeto que contiene el contenido.
Llamar a json_validate() inmediatamente antes de json_decode() analizará innecesariamente la string dos veces, ya que json_decode() realiza implícitamente una validación durante la decodificación.
json_validate() no debe ser utilizado a menos que la decodificación del contenido JSON no sea inmediatamente utilizada y que sea necesario saber si la string contiene JSON válido.
jsonLa string a validar.
Esta función solo funciona con strings codificadas en UTF-8.
Nota: PHP implementa un superconjunto de JSON tal como se especifica en el » RFC 7159 original.
depth
El nivel máximo de profundidad de la estructura a decodificar.
El valor debe ser mayor que 0,
y menor o igual a 2147483647.
flags
Actualmente, solo
JSON_INVALID_UTF8_IGNORE
es aceptado.
Devuelve true si la string dada es sintácticamente JSON válido, de lo contrario
devuelve false .
Si depth está fuera del rango permitido,
se lanza una ValueError .
Si flags no es un flag válido,
se lanza una ValueError .
Ejemplo #1 Ejemplos de json_validate()
<?php
var_dump(json_validate('{ "test": { "foo": "bar" } }'));
var_dump(json_validate('{ "": "": "" } }'));
?>El ejemplo anterior mostrará:
bool(true) bool(false)
---------------- PHP < 8.3 ----------------
function json_validate(string $string): bool {
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
var_dump(json_validate('{ "test": { "foo": "bar" } }')); // true
---------------- PHP >= 8.3 ----------------
var_dump(json_validate('{ "test": { "foo": "bar" } }')); // true
Note: code from https://www.php.net/releases/8.3/en.php Building upon Allan R.'s initial idea, I've developed an improved version of the json_validate function for those using PHP 8.2 and earlier versions. This function emulates the functionality introduced in PHP 8.3, providing an effective way to validate JSON strings in earlier PHP versions.
```php
if (!function_exists('json_validate')) {
/**
* Validates a JSON string.
*
* @param string $json The JSON string to validate.
* @param int $depth Maximum depth. Must be greater than zero.
* @param int $flags Bitmask of JSON decode options.
* @return bool Returns true if the string is a valid JSON, otherwise false.
*/
function json_validate($json, $depth = 512, $flags = 0) {
if (!is_string($json)) {
return false;
}
try {
json_decode($json, false, $depth, $flags | JSON_THROW_ON_ERROR);
return true;
} catch (\JsonException $e) {
return false;
}
}
}
```
Key Improvements:
- String Check: Added a validation to ensure the input is a string.
- Error Handling: Utilizes try-catch to effectively catch and handle JsonException.
- Backward Compatibility: Safely integrable in older PHP versions, automatically deferring to native functionality in PHP 8.3+.Please note that this will return true if the value is numerical, whether it's of type int/float, or a string. This is something to be aware of if you're expecting an array/object, which may cause issues down the line when handling it.