Home » Programming » PHP » Php Validate Json

A Trick for Validating JSON in PHP

Here’s a quick trick for validating JSON in PHP – with a reusable function, you can copy and paste it into your own project.

JSON has pretty much become the standard format for transferring data between applications on the internet. So if you’re building an API to be consumed by others or just building a backend for your app, you’ll be sending and receiving a lot of JSON data.

But, you can never trust the request – the data coming into your application. Users enter bad data. Hackers deliberately enter bad data. Computers misfire and enter bad dataBad data will be submitted to your PHP app.

So what are you mean to do about it? First, sanitize the data, and check that it’s valid.

Function to Check for Valid JSON in PHP

Below is a quick function that will validate whether or not a given string is valid JSON:

function validateJSON(string $json): bool {

    try {
        $test = json_decode($json, null, flags: JSON_THROW_ON_ERROR);
        return true;
    } catch  (Exception $e) {
        return false;
    }

}

This function is ready for use in your project; just copy and paste it where you need it.

Here it is in action:

if(validateJSON('[]')) {
    // This if statement will succeed, as '[]' is valid JSON (it's just an empty array)
}

if(validateJSON('qwerty')) {
    // This if statement will fail, as 'qwerty' is NOT valid JSON
}

How Does it Work?

This is a pretty simple bit of code that wraps the json_decode() function.

The json_decode function does what it says – it decodes a JSON string and converts it to a PHP object.

By default, json_decode() will return NULL if it is unable to parse the given string. Above, the JSON_THROW_ON_ERROR flag is passed to it, which will force it to throw an error if invalid JSON is encountered.

By surrounding that with a try/catch statement, we can prevent the error from stopping the application and instead tell the function to return FALSE if an error occurs. If the JSON is valid, no error will be thrown, and TRUE will be returned.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment