Check if String is a Valid Json in PHP

This tutorial will discuss about unique ways to check if string is a valid json in php.

Table Of Contents

Method 1: Using json_decode()

The json_decode() accepts a JSON encoded string as parameter, and if it is a valid json string then it converts the string into a PHP value. Where if it is not a valid JSON then the last error will not be JSON_ERROR_NONE.

We have create a function to validate JSON string i.e.

function isStringJson($str)
{
    json_decode($str);
    return (json_last_error() === JSON_ERROR_NONE);
}

It accepts a string as argument and returns true if given string is a valid JSON string.

Let’s see the complete example,

<?php
/**
 * Checks if a string represents a valid JSON
 * using json_decode().
 *
 * @param string $str The string to check.
 * @return bool True if the string is valid JSON, false otherwise.
 */
function isStringJson($str)
{
    json_decode($str);
    return (json_last_error() === JSON_ERROR_NONE);
}

$strValue = '{
                "name":  "Ritika",
                "age" :  32,
                "city":  "London"
            }';

if (isStringJson($strValue)) {
    echo "The string represents valid JSON.";
} else {
    echo "The string does not represent valid JSON.";
}
?>

Output

The string represents valid JSON.

Method 2: Using json_decode() with error suppression

If error suppression is enabled, then we can rely on the return valud of json_decode().

The json_decode() accepts a JSON encoded string as parameter, and if it is a valid json string then it converts the string into a PHP value. If it is not a valid JSON string then it returns null.

We have create a function to validate JSON string i.e.

function isValidJSON($str)
{
    return (json_decode($str) !== null);
}

It accepts a string as argument and returns true if given string is a valid JSON string.

Let’s see the complete example,

<?php
/**
 * Checks if a string represents a valid JSON using json_decode()
 * with error suppression.
 *
 * @param string $str The string to check.
 * @return bool True if the string is valid JSON, false otherwise.
 */
function isValidJSON($str)
{
    return (json_decode($str) !== null);
}

$strValue = '{"name":"Ritika","age":32,"city":"London"}';

if (isValidJSON($strValue)) {
    echo "The string represents valid JSON.";
} else {
    echo "The string does not represent valid JSON.";
}
?>

Output

The string represents valid JSON.

Summary

We learned about two ways to check if a string is a valid JSON string or not in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top