Skip to Content
Course content

28: Working with JSON in PHP

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

I've seen this happen more times than I can count: a developer gets a JSON string from an API and, because they need to change one single value, they try to use str_replace() or preg_replace() to swap out a value directly in the string. It seems faster, right? Why bother decoding the whole thing if you just want to change "status": "pending" to "status": "complete"?

Stop treating JSON as a string

Let me show you why that approach is a disaster waiting to happen. Imagine you have a JSON string representing a user profile:

$json = '{"username": "dark_knight", "theme": "dark", "status": "active"}';
// The "clever" way to change the theme to light
$json = str_replace("dark", "light", $json);
echo $json; 
// Result: {"username": "light_knight", "theme": "light", "status": "active"}

Oops. You didn't just change the theme; you accidentally renamed the user to "light_knight". This is why treating JSON as raw text is a cardinal sin in software engineering. JSON is a data format, not just a string. To work with it safely, you have to move the data from the "JSON world" into the "PHP world," make your changes, and then ship it back.

The Decode-Modify-Encode Cycle

The correct workflow is a three-step cycle. First, we use json_decode() to turn that string into something PHP actually understands—either an object or an associative array. Then we change the data using standard PHP syntax. Finally, we use json_encode() to turn it back into a string for storage or transmission.

There's one detail here that trips people up: the second argument of json_decode(). By default, it returns an object of the stdClass type. But in my experience, most PHP developers find associative arrays much easier to manipulate.

$json = '{"username": "dark_knight", "theme": "dark", "status": "active"}';

// Pass 'true' as the second argument to get an associative array
$data = json_decode($json, true);

// Now we can safely target only the 'theme' key
$data['theme'] = 'light';

// Convert it back to a JSON string
$updatedJson = json_encode($data);

If you omit that true, you'd have to use object notation ($data->theme = 'light';). Both work, but be consistent. Mixing them in one project is a recipe for "Undefined property" errors that will waste your entire afternoon.

Handling API Errors and Nulls

In a perfect world, every API sends back valid JSON. In the real world, APIs crash, return HTML error pages instead of JSON, or send back empty strings. If json_decode() fails, it returns null.

I highly recommend checking the result before you try to access any keys. If you try to treat null as an array, PHP will throw a warning. I usually wrap my decoding in a simple check or use json_last_error() if I need to know exactly why the parsing failed (like a trailing comma that shouldn't be there).

$json = '{"invalid": json}'; // This is malformed JSON
$data = json_decode($json, true);

if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
    // Log the error or tell the user the API is acting up
    die("JSON Error: " . json_last_error_msg());
}

One last pro tip: when encoding data to send to a browser or another API, use the JSON_PRETTY_PRINT flag. It doesn't change the data, but it adds whitespace and line breaks, making it actually readable for humans when you're debugging in the browser network tab.

echo json_encode($data, JSON_PRETTY_PRINT);



📋 Practical Task

The Game Inventory Sync System

You are building a synchronization tool for a multiplayer game. You receive a JSON string representing a player's inventory, but you need to update it based on a recent loot drop before saving it back to the database.

Your Task:

  1. Start with this JSON string: '{"player": "Zeldar", "level": 12, "inventory": {"potions": 3, "arrows": 50, "gold": 120}}'
  2. Decode the string into a PHP associative array.
  3. Add 2 to the potions count.
  4. Add a new item to the inventory: "magic_scroll" with a value of 1.
  5. Increase the level by 1.
  6. Encode the modified array back into a JSON string using JSON_PRETTY_PRINT and echo the result.

Note: Ensure you are using the associative array approach (the second parameter of json_decode) to handle the nested inventory data.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.