0

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

3
  • 1
    @Yoshi validate_json function added Commented Oct 8, 2021 at 8:49
  • Have you tried to debug your function? It's probably count($results) < 1 that gives you false on a empty json object... Commented Oct 8, 2021 at 8:51
  • @AdityaRewari What would valid json look like? Do you want to know if it's valid json in general or according to some specs of yours? Commented Oct 8, 2021 at 8:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.