Introduction
As PHP developers, we often work with JSON. On an almost daily basis, I interact with JSON when receiving data from an API, reading configuration files, returning API responses from my Laravel apps, accepting JSON input from users, and more.
There may be times when we need to validate whether a given string is valid JSON. This is especially important when dealing with user input or data from external sources, where the format may not be guaranteed.
In this Quickfire article, we'll explore how to check whether a string is valid JSON in PHP using the built-in json_validate
function.
Check if a String is Valid JSON in PHP
The json_validate
function was introduced in PHP 8.3 (released in November 2023) as a simple and efficient way to validate JSON strings.
It accepts a string as input and returns true
if the string is valid JSON, or false
otherwise.
For example, here's how we could use json_validate
:
1$jsonString = '{"name": "John", "age": 30, "city": "London"}';2 3$isValid = json_validate($jsonString);4 5// $isValid will be true
And here's an example of it returning false
for an invalid JSON string:
1// Missing closing brace2$invalidJsonString = '{"name": "John", "age": 30, "city": "London"';3 4$isValid = json_validate($invalidJsonString);5 6// $isValid will be false
As you can see, json_validate
provides a straightforward way to check the validity of a JSON string.
However, it's important to remember that it isn't checking the contents of the JSON, just whether the string is properly formatted as JSON. For example, we can't use json_validate
to check if a JSON string contains specific keys or values. If you want to do this, you'll need to decode the JSON and then inspect the resulting data structure.
Retrieving the Error Message
If the json_validate
function returns false
, you can use json_last_error()
to get the error code and json_last_error_msg()
to get a descriptive error message. This is useful for debugging purposes or for providing feedback to users.
Let's see an example of this in action:
1// Missing closing brace 2$invalidJsonString = '{"name": "John", "age": 30, "city": "London"'; 3 4$isValid = json_validate($invalidJsonString); 5 6if (!$isValid) { 7 $errorCode = json_last_error(); 8 $errorMessage = json_last_error_msg(); 9}10 11// $errorCode will be: 4 (JSON_ERROR_SYNTAX)12// $errorMessage will be: "Syntax error"
For a full list of the possible error codes and their meaning, you can refer to the PHP documentation for json_last_error().
"json_validate" vs "json_decode"
You might be reading this and wondering, "Why not just use json_decode
to check if a string is valid JSON?".
And that's a fair question!
In fact, there might be situations where you actually want to opt for json_decode
instead of json_validate
.
When you use json_decode
, it implicitly validates the JSON as part of its operation. If the JSON is valid, it will return the decoded data structure (array or object). If the JSON is invalid, it will return null
, and you can use json_last_error()
to retrieve the error code (or use the JSON_THROW_ON_ERROR
flag to throw an exception if the JSON is invalid).
However, json_decode
can be more memory-intensive because it needs to build the data structure (e.g., arrays, objects, etc.) from the JSON string. In a lot of cases, this might be exactly what you want, especially if you're going to use the decoded data right away. But in other cases, you might not want to use the JSON immediately. You might just want to check whether it's valid before passing it on to something like a database, cache, or a queued job for processing later. In these scenarios, loading the entire data structure into memory is unnecessary overhead.
Granted, the memory difference might be negligible for small JSON strings, but it may become more significant when dealing with large JSON payloads or high-throughput applications. So if you're not immediately using the decoded data, json_validate
is a more efficient choice because it doesn't need to build the data structure; it just checks the validity of the JSON string.
Don't Parse the JSON Twice
It's important to remember that json_validate
and json_decode
both need to parse the JSON string to perform their operations. So if you use json_validate
and then immediately follow it with json_decode
, you're parsing the JSON string twice, which is inefficient.
As we've already mentioned, json_decode
already validates the JSON as part of its operation. So you don't need to use json_validate
first if you're going to decode the JSON right away.
json_validate
is most useful when you only want to check the validity of a JSON string, and then want to process it elsewhere later.
Related Reading
You might be interested in checking out my related article, which covers how to read JSON files in your Laravel applications:
Conclusion
Hopefully, this Quickfire article has given you a good understanding of how to check if a string is valid JSON in PHP using the new json_validate
function.
If you enjoyed reading this post, you might be interested in checking out my 220+ page ebook "Battle Ready Laravel" which covers similar topics in more depth.
Or, you might want to check out my other 440+ page ebook "Consuming APIs in Laravel" which teaches you how to use Laravel to consume APIs from other services.
If you're interested in getting updated each time I publish a new post, feel free to sign up for my newsletter below.
Keep on building awesome stuff! 🚀