validate print empty ejemplo correct check php json well-formed

print - validate json decode php



¿Cómo validar JSON en PHP? (5)

¿Hay alguna forma de verificar que una variable sea una cadena JSON válida en PHP sin usar json_last_error() ? No tengo PHP 5.3.3.


Además, puede consultar http://php.net/manual/en/function.json-last-error-msg.php que contiene implementaciones de la función que falta.

Uno de ellos es:

if (!function_exists(''json_last_error_msg'')) { function json_last_error_msg() { static $ERRORS = array( JSON_ERROR_NONE => ''No error'', JSON_ERROR_DEPTH => ''Maximum stack depth exceeded'', JSON_ERROR_STATE_MISMATCH => ''State mismatch (invalid or malformed JSON)'', JSON_ERROR_CTRL_CHAR => ''Control character error, possibly incorrectly encoded'', JSON_ERROR_SYNTAX => ''Syntax error'', JSON_ERROR_UTF8 => ''Malformed UTF-8 characters, possibly incorrectly encoded'' ); $error = json_last_error(); return isset($ERRORS[$error]) ? $ERRORS[$error] : ''Unknown error''; } }

(Copiado pegado del sitio)


Podrías comprobar si el valor de json_decode es null . Si es así, es inválido.


Si desea verificar si su entrada es JSON válida, también podría estar interesado en validar si sigue un formato específico, es decir, un esquema. En este caso, puede definir su esquema utilizando el esquema JSON y validarlo utilizando esta library .

Ejemplo:

persona.json

{ "title": "Person", "type": "object", "properties": { "firstName": { "type": "string" }, "lastName": { "type": "string" }, "age": { "description": "Age in years", "type": "integer", "minimum": 0 } }, "required": ["firstName", "lastName"] }

Validación

<?php $data = ''{"firstName":"Hermeto","lastName":"Pascoal"}''; $validator = new JsonSchema/Validator; $validator->validate($data, (object)[''$ref'' => ''file://'' . realpath(''person.json'')]); $validator->isValid()


$data = json_decode($json_string); if (is_null($data)) { die("Something dun gone blowed up!"); }


$ob = json_decode($json); if($ob === null) { // $ob is null because the json cannot be decoded }