Open In App

How to Validate JSON in PHP ?

In this article, we will see how to validate JSON strings in PHP. 

JSON is an abbreviation for JavaScript Object Notation. It is an extensively used data interchange format for online services that are easily understood by humans. To determine if the JSON output is genuine, PHP includes a method called json_decode(), which was introduced in PHP 5.3. 



It is a PHP built-in function that is used to decode a JSON string. It creates a PHP variable from a JSON encoded text.

Syntax: 



json_decode( $json, $assoc = FALSE, $depth = 512, $options = 0 )

Parameters: As previously stated, this function requires four parameters:

Return values: The encoded JSON value is returned in the proper PHP type by this method. It returns NULL if the JSON cannot be decoded if the encoded data is deeper than the recursion limit.

Example 1: The following code demonstrates the validation of JSON in PHP by using the following methods.

if (!empty($data))
is_string($data)
is_array(json_decode($data, true))




<?php
    function json_validator($data) {
        if (!empty($data)) {
            return is_string($data) && 
              is_array(json_decode($data, true)) ? true : false;
        }
        return false;
    }
  
    $data1 = '{"name":"vishal", "email": "abc@gmail.com"}';
    $data2 = '{name:vishal, email: abc@gmail.com}';
  
    echo "Result for data1: ";
    echo (json_validator($data1) ? "JSON is Valid\n" 
        : "JSON is Not Valid\n");
    echo "Result for data2: ";
    echo (json_validator($data2) ? "JSON is Valid" 
        : "JSON is Not Valid");
?>

Output:

 

Example 2: If the string is legitimate, json_decode will process it and return the PHP variable. If the string is invalid, the error will be generated. The error will be suppressed by the character “@”.

@json_decode($data)

This will determine whether $data is a valid JSON string by comparing it to JSON_ERROR_NONE. The json_last_error() returns the last error if there were any errors when json_decode() was invoked.

return (json_last_error() === JSON_ERROR_NONE)




<?php
    function json_validator($data) {
        if (!empty($data)) {
            @json_decode($data);
            return (json_last_error() === JSON_ERROR_NONE);
        }
        return false;
    }
  
    $data1 = '{"name":"vishal", "email": "abc@gmail.com"}';
    $data2 = '{name:vishal, email: abc@gmail.com}';
  
    echo "Result for data1: ";
    echo (json_validator($data1) ? "JSON is Valid\n" 
        : "JSON is Not Valid\n");
    echo "Result for data2: ";
    echo (json_validator($data2) ? "JSON is Valid" 
        : "JSON is Not Valid");
?>

Output:

 


Article Tags :