Skip to Content
Course content

110: json_encode and json_decode Options

Click on the "Edit" button in the top corner of the screen to edit your slide content.

By now, you've likely used json_encode and json_decode a dozen times. They seem straightforward: one turns a PHP variable into a string, and the other turns that string back into a variable. But if you're just calling them without any options, you're essentially playing a game of "I hope the data is formatted exactly how I expect," which is a recipe for a 3:00 AM production bug.

The Object vs. Array Headache

The most common mistake I see is the naive use of json_decode($json). By default, this returns a stdClass object. Now, objects are fine, but in PHP, we spend most of our time manipulating associative arrays. When you get an object back, you're forced to use the -> syntax. This sounds trivial until you're trying to iterate over the data or pass it into a function that expects an array.

// The naive way
$data = json_decode($json_string);
echo $data->user->name; // This works, but it's rigid.

I always recommend passing true as the second argument. This tells PHP to convert everything into an associative array. It makes the data much more flexible to work with, especially when you're using array functions like array_map or array_filter. It's a small change, but it saves you from constantly casting objects to arrays later in your pipeline.

// The better way
$data = json_decode($json_string, true);
echo $data['user']['name']; // Much more natural for PHP developers.

Silent Failures and the Modern Fix

Here is where things get dangerous. Traditionally, if json_decode failed because of a syntax error in the JSON string, it would simply return null. If you weren't explicitly checking json_last_error() after every single call—which, let's be honest, almost nobody does—your code would just keep running with a null value until it hit a "trying to access array offset on value of type null" error five functions later. Tracking that back to the source is a nightmare.

Since PHP 7.3, we have JSON_THROW_ON_ERROR. I consider this mandatory. Instead of returning null and hoping for the best, this flag forces PHP to throw a JsonException. I'd much rather have my application crash immediately with a clear error message than have it silently fail and corrupt a database record because a comma was missing in the API response.

// The risky way
$data = json_decode($json_string, true); 
// If $json_string is malformed, $data is null. Silence.

// The professional way
try {
    $data = json_decode($json_string, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
    // Log it, alert the team, or return a 400 Bad Request
    error_log("JSON Decode Error: " . $e->getMessage());
}

Handling Unicode and Human Readability

When you're encoding data to send to a browser, json_encode($data) is usually enough. But what happens when your data contains accented characters or emojis? By default, PHP escapes these as Unicode sequences (like \u00e9). While this is technically correct and safe, it's a pain to debug in your logs.

If you're writing JSON to a log file or a config file that a human needs to read, use JSON_PRETTY_PRINT and JSON_UNESCAPED_UNICODE. The first adds whitespace and indentation, and the second keeps your characters as they are. I've spent way too many hours staring at a wall of minified JSON trying to find a missing key; pretty-printing is a gift to your future self.

$user_profile = [
    'name' => 'André',
    'bio' => '🚀 Software Engineer',
    'settings' => ['theme' => 'dark', 'notifications' => true]
];

// Naive: one long, escaped string
echo json_encode($user_profile); 

// Better: Readable and clean
echo json_encode($user_profile, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

Just keep in mind that JSON_PRETTY_PRINT increases the payload size. Don't use it for high-traffic API responses where every byte counts, but absolutely use it for debugging and configuration files.




📋 Practical Task

Exercise: Robust API Response Parser

You are building a module that consumes a Product Catalog API. The API is known to be flaky—sometimes it sends malformed JSON, and the product descriptions often contain special characters and emojis.

Your Task: Write a PHP script that does the following:

  • Define a string variable $api_response containing the following JSON: '{"product_name": "Café Espresso Machine ☕", "price": 299.99, "tags": ["kitchen", "luxury"]}'.
  • Decode this string into an associative array.
  • Wrap the decoding process in a try-catch block using the JSON_THROW_ON_ERROR flag to handle any potential JsonException.
  • Once decoded, use json_encode to print the array back to the screen, but ensure the output is pretty-printed and the Unicode characters (like the emoji and the 'é') are not escaped.

Test your error handling by intentionally removing a quote or a bracket from the $api_response string and ensuring your catch block handles the failure gracefully.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.