Home > OS >  Unable to validate empty json object in PHP
Unable to validate empty json object in PHP

Time:10-08

Surprisingly, validate_json function is returning false at an empty json object;

$empty_json_obj = "{}";
if(validate_json($empty_json_obj)) {
    print_r("VALID");
} 
else {
    print_r("NOT VALID");
}

Output NOT VALID

validate_json function

function validate_json($data) {
    if ( ! $data) {
        return FALSE;
    }

    $result = (array) json_decode($data);
    if ( ! is_array($result) || count($result) < 1) {
        return FALSE;
    }

    return TRUE;
}

How to get this right, so that validate_json identify correctly empty json passed as json

CodePudding user response:

If you simply want to test whether the content of a given string is valid JSON or not, it's quite straightforward.

The manual page for json_decode says:

null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting limit.

Therefore all you really need to do is test for null. Casting to arrays etc is unnecessary (and not every piece of valid JSON is translateable to an array anyway - objects are also very common).

function validate_json($data) {
    if ( ! $data) {
        return FALSE;
    }

    $result = json_decode($data);
    if ($result === null) {
        return FALSE;
    }

    return TRUE;
}

N.B. If validation fails you can then use json_last_error() and/or json_last_error_msg() to find out what the problem was.

  • Related