Check if String is Valid JSON using PHP

json_decode function with JSON_THROW_ON_ERROR flag

<?php

function isJson(string $value): bool
{
    try {
        json_decode($value, true, 512, JSON_THROW_ON_ERROR);
    } catch (JsonException) {
        return false;
    }

    return true;
}

echo isJson('{"name":"John"}') ? 'Yes' : 'No';
echo isJson('{0,1,3}') ? 'Yes' : 'No';

Leave a Comment

Cancel reply

Your email address will not be published.