AdnanTech PHP Check if string is valid JSON array or object – PHP

Check if string is valid JSON array or object – PHP

Check if string is valid JSON array or object in PHP using PHP build-in functions. There are 2 ways to check the validity.

1st method (json_decode)

If you are getting a PHP variable who’s value can be either a JSON array or an JSON object, and you want to check if the JSON string is either an array or an object, then you can use PHP built-in json_decode function.

This function accepts the string as a parameter and return the decoded array or object. If it fails to decode the JSON string, it will return the null value.

2nd method (json_last_error)

Second method to check the validity of JSON string is to use the PHP built-in json_last_error function. This will return the error code of last decode attempt on JSON string. It returns a numerical value. 0 means there is no error. An enum JSON_ERROR_NONE can be used to compare the value. You can check all other possible values from PHP official documentation.

3rd method (json_validate, requires PHP >= 8.3)

However, there is a third method too but it requires PHP >= 8.3. It is the latest version of PHP at the time of writing this. So it is not upgraded in many of the websites, that is why you should use this only when you are sure that your site is running on PHP 8.3 or above. A new function json_validate is introduction in PHP 8.3. It accepts only 1 parameter, a JSON string, and return true or false if the string is a valid JSON or not.

Here is the complete code on how you can do that:

<?php

$json = "adnan-tech.com";

$json = '["Adnan"]';

$json = '{"name": "Adnan"}';

echo $json . " = ";

// if (json_validate($json))
// {

// }

$result = json_decode($json);

// if (json_last_error() === JSON_ERROR_NONE)

if ($result != null)
{
    echo "Valid <br />";

    if (is_array($result))
    {
        echo "Array";
    }

    if (is_object($result))
    {
        echo "Object";
    }
}
else
{
    echo "In-valid";
}

I have given 3 possible values of JSON string.

  1. It can be an in-valid string.
  2. It can be a valid array.
  3. It can be a valid object.

Also, I have written both 2 conditions that can be used to check the validity of JSON string.

That’s how you can check if the string is valid JSON array or an object in PHP. If you want to know how to encode the data from database into an array, check our tutorial.

Related Post