json_validate

(PHP 8 >= 8.3.0)

json_validateChecks if a string contains valid JSON

Описание

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

Returns whether the given string is syntactically valid JSON. If json_validate() returns true, json_decode() will successfully decode the given string when using the same depth and flags.

If json_validate() returns false, the cause can be retrieved using json_last_error() and json_last_error_msg().

json_validate() uses less memory than json_decode() if the decoded JSON payload is not used, because it does not need to build the array or object structure containing the payload.

Предостережение

Calling json_validate() immediately before json_decode() will unnecessarily parse the string twice, as json_decode() implicitly performs validation during decoding.

json_validate() should therefore only be used if the decode JSON payload is not immediately used and knowing whether the string contains valid JSON is needed.

Список параметров

json

The string to validate.

This function only works with UTF-8 encoded strings.

Замечание:

PHP реализует надмножество JSON, который описан в первоначальном » RFC 7159.

depth

Maximum nesting depth of the structure being decoded. The value must be greater than 0, and less than or equal to 2147483647.

flags

Currently only JSON_INVALID_UTF8_IGNORE is accepted.

Возвращаемые значения

Returns true if the given string is syntactically valid JSON, otherwise returns false.

Ошибки

If depth is outside the allowed range, a ValueError is thrown.

Примеры

Пример #1 json_validate() examples

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

Результат выполнения данного примера:

bool(true)
bool(false)

Смотрите также

  • json_decode() - Декодирует строку JSON
  • json_last_error() - Возвращает последнюю ошибку
  • json_last_error_msg() - Возвращает строку с сообщением об ошибке последнего вызова json_encode() или json_decode()