Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate JSON in PHP older than 5.3.0?

People also ask

How check JSON is valid or not in PHP?

we can use json_last_error() PHP function to check validity of JSON, It returns JSON_ERROR_NONE predefined constant value if JSON successfully decoded or encoded by PHP's josn functions.

How can I check JSON data in PHP?

Simple function to validate JSON. If you have to validate your JSON in multiple places, you can always use the following function. function is_valid_json( $raw_json ){ return ( json_decode( $raw_json , true ) == NULL ) ? false : true ; // Yes!

How do I check if a JSON file is valid?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema. To get validation error messages use the IsValid(JToken, JSchema, IList<String> ) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.

What is JSON formatter and validator?

JSON Formatter and JSON Validator help to auto format JSON and validate your JSON text. It also provides a tree view that helps to navigate your formatted JSON data. It helps to validate JSON online with Error Messages. It's the only JSON tool that shows the image on hover on Image URL in a tree view.


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

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

If you want to check if your input is valid JSON, you might as well be interested in validating whether or not it follows a specific format, i.e a schema. In this case you can define your schema using JSON Schema and validate it using this library.

Example:

person.json

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

Validation

<?php

$data = '{"firstName":"Hermeto","lastName":"Pascoal"}';

$validator = new JsonSchema\Validator;
$validator->validate($data, (object)['$ref' => 'file://' . realpath('person.json')]);

$validator->isValid()

Furthermore you can have a look on http://php.net/manual/en/function.json-last-error-msg.php that contain implementations of the missing function.

One of them is:

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';
        }
    }

(Copied pasted from the site)