phpday 2027 - Call for Papers

json_validate

(PHP 8 >= 8.3.0)

json_validate — Verifica se una stringa contiene JSON valido

Descrizione

function json_validate(string $json, int $depth = 512, int $flags = 0): bool

Restituisce se la string fornita è sintatticamente un JSON valido. Se json_validate() restituisce true, json_decode() decodificherà con successo la stringa fornita se si usano gli stessi valori di depth e flags.

Se json_validate() restituisce false, la causa può essere recuperata con json_last_error() e json_last_error_msg().

json_validate() usa meno memoria di json_decode() se il contenuto JSON decodificato non viene utilizzato, perché non deve costruire la struttura di array o oggetti che contiene il contenuto.

Attenzione

Chiamare json_validate() immediatamente prima di json_decode() analizzerà inutilmente la stringa due volte, poiché json_decode() esegue implicitamente la validazione durante la decodifica.

json_validate() dovrebbe quindi essere usata solo se il contenuto JSON decodificato non viene utilizzato immediatamente e occorre sapere se la stringa contiene JSON valido.

Elenco dei parametri

json

La stringa da validare.

Questa funzione funziona solo con stringhe codificate in UTF-8.

Nota:

PHP implementa un superset di JSON come specificato nella » RFC 7159 originale.

depth

Profondità massima di annidamento della struttura da decodificare. Il valore deve essere maggiore di 0 e minore o uguale a 2147483647.

flags

Attualmente è accettato solo JSON_INVALID_UTF8_IGNORE.

Valori restituiti

Restituisce true se la stringa fornita è sintatticamente un JSON valido, altrimenti restituisce false.

Errori/Eccezioni

Se depth è al di fuori dell'intervallo consentito, viene generata un'eccezione ValueError.

Se flags non è un flag valido, viene generata un'eccezione ValueError.

Esempi

Example #1 Esempi di json_validate()

<?php
var_dump(json_validate('{ "test": { "foo": "bar" } }'));
var_dump(json_validate('{ "": "": "" } }'));
?>

Il precedente esempio visualizzerà:

bool(true)
bool(false)

Vedere anche:

User Contributed Notes 3 notes

up
26
Behrad
2 years ago
---------------- 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
up
18
Julien T.
2 years ago
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+.
up
0
c dot smith at fantasticmedia dot co dot uk
1 year ago
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.
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top