Skip to content

How to Check if a String is Valid JSON in PHP

Learn when to use PHP 8.3's new json_validate() vs traditional json_decode() for JSON validation. Includes performance benchmarks, real-world examples, and best practices for efficient JSON handling in PHP applications.

Dasun Kalupahana 2 min read 1.1K views 0 comments

Handling JSON data is a daily task for most PHP developers. Whether you're processing API responses, reading configuration files, or storing data, ensuring that a string is valid JSON before you use it is crucial. For years, we relied on json_decode() for this, but with the release of PHP 8.3, we now have a dedicated tool: json_validate().

Let's explore this new function, compare it with the old method, and discuss when to use each.


The New Kid on the Block: json_validate()

Introduced in PHP 8.3, json_validate() is the most straightforward way to check a string's JSON validity. It does one job and does it well:

  • Accepts: A string.

  • Returns: true if the string is valid JSON, false otherwise.

Example: The Basics

// Valid JSON
$validJson = '{"name": "Alice", "age": 28, "pets": ["Dog", "Cat"]}';
$isValid = json_validate($validJson);
var_dump($isValid); // Output: bool(true)

// Invalid JSON (trailing comma)
$invalidJson = '{"name": "Alice", "age": 28,}';
$isValid = json_validate($invalidJson);
var_dump($isValid); // Output: bool(false)

As you can see, it's incredibly simple. However, a false result doesn't tell us what went wrong. For that, we need to dig a little deeper.


Getting the Error Details

When json_validate() returns false, PHP stores an error code and message. You can retrieve them using json_last_error() and json_last_error_msg(). This is perfect for logging or user feedback.

Example: Debugging an Invalid JSON String

$brokenJson = '{"website": "https://example.com"}'; // Missing closing quote and brace

if (!json_validate($brokenJson)) {
    $errorCode = json_last_error();
    $errorMessage = json_last_error_msg();
    
    echo "Error Code: " . $errorCode . "\n"; // Output: Error Code: 4
    echo "Error Message: " . $errorMessage . "\n"; // Output: Error Message: Syntax error
}

Pro Tip: Common error codes include 4 for JSON_ERROR_SYNTAX and 5 for JSON_ERROR_DEPTH (exceeding the recursion limit). Check the PHP documentation for the full list.


The Classic Approach: json_decode()

You might be wondering, "We already had json_decode(). Why do we need a new function?" It's a great question.

json_decode() has always been a de facto validator. If you pass it invalid JSON, it returns null. You can check for this.

Example: Validation with json_decode()

$questionableJson = 'This is not JSON';

$data = json_decode($questionableJson);

if ($data === null) {
    echo "This is invalid JSON!";
    // You can also use json_last_error() here to find out why.
} else {
    echo "Valid JSON! Proceed to use the data.";
    // $data is now a PHP object or array.
}

With the JSON_THROW_ON_ERROR flag (introduced in PHP 7.3), it gets even cleaner, as it throws an exception you can catch.

try {
    $data = json_decode($questionableJson, flags: JSON_THROW_ON_ERROR);
    // If we get here, JSON is valid and $data is ready.
} catch (JsonException $e) {
    echo "JSON error: " . $e->getMessage();
}

So, if json_decode() can both validate and give you the data, why would you ever use json_validate()? The answer lies in performance and intent.


json_validate() vs. json_decode(): Which Should You Use?

The choice comes down to one question: What do you plan to do with the JSON data right now?

Use json_decode() when:

You need to use the data immediately in your script.

// You are processing an API response NOW.
$apiResponse = '{"user_id": 123, "email": "alice@example.com"}';
$userData = json_decode($apiResponse);

if ($userData !== null) {
    echo "Welcome, User #" . $userData->user_id; // Using the data right away.
}

In this case, json_validate() would be a waste. You'd validate the string and then immediately decode it, parsing the JSON twice.

Use json_validate() when:

You only need to check the validity before storing or queuing the data for later.

// You are saving a JSON string to a database or a cache system.
$userProvidedJson = $_POST['user_config'];

// You don't need the data now, you just need to know it's valid.
if (json_validate($userProvidedJson)) {
    // It's safe to store the raw string in the database.
    $db->saveConfig($currentUserId, $userProvidedJson);
    echo "Configuration saved!";
} else {
    echo "Invalid JSON provided. Please check your syntax.";
}

Why is this more efficient? json_decode() must parse the entire string and build a potentially large, complex PHP data structure in memory. json_validate(), on the other hand, only needs to check the syntax without constructing anything. For small JSON snippets, the difference is negligible, but for large payloads or high-traffic applications, this can save significant memory and CPU cycles.


Key Takeaway: Don't Parse Twice!

The most important rule to remember is to avoid validating and then decoding in sequence.

❌ Inefficient:

// Don't do this!
if (json_validate($jsonString)) {
    $data = json_decode($jsonString); // The JSON was just parsed twice!
    // ... use $data
}

✅ Efficient:

// If you need the data, just decode it. It validates implicitly.
$data = json_decode($jsonString);
if ($data !== null) {
    // ... use $data
}

// Or, if you DON'T need the data, just validate it.
if (json_validate($jsonString)) {
    // ... store or queue $jsonString for later
}

By choosing the right tool for the job, you write cleaner, more intentional, and more performant code. Happy coding.

Free resources for this topic

Code snippets and fixes for this topic

Get one practical tip every week

New tutorials, fixes and free cheat sheets from DEV Talk, straight to your inbox. No spam, unsubscribe in one click.

Free download: Laravel interview questions (PDF)

Have a question about this post?

Ask the community: other developers and the author can answer.

Ask the community

Get notified about new articles

One click, no email needed. Turn it off anytime with the bell at the top.

Get new articles on your iPhone

Add DEV Talk to your Home Screen, open it, then tap the bell.

Rate this post
0.0
Share

Enjoying the content?

If this article helped you, you can support the author with a coffee. It keeps new posts coming.

Buy me a coffee (opens in a new tab)

Comments 0

Be kind. Comments with links are reviewed before they appear.

No comments yet

Be the first to share your thoughts.

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.