Skip to content

How To Handle JSON Objects With PHP

Working with JavaScript for an extended period of time can make you take many things for granted that aren’t as easy to do in other programming languages, one of them being JSON handling. Since JSON is derived from the JavaScript language, they share much of the same syntax. Naturally, this makes them particularly well suited for each other. However, handling this data format in another language such as PHP isn’t as straightforward as you might hope and it can take some time getting used to. 😥 In this article, I hope to give you an overview on this topic and help you get started on how to handle JSON objects with PHP.

Please note that I will not cover what JSON actually is and how it works. For that, I recommend this fine article by Copter Labs.

Encoding and decoding JSON

Since version 5.2, PHP features two built-in functions to transform your PHP data structures into JSON and vice versa:

  • json_encode(mixed $value); transforms a PHP data structure into a JSON object
  • json_decode(string $json); transforms a JSON object into a PHP data structure
Batman slaps Robin meme: Keep reading the "How To Handle JSON Objects With PHP" article
Not so fast! ✋

Now, slapping any PHP data structure into the former function won’t always work the way you expect it to. Here’s what you need to pay attention to.

Watch out for indexed arrays

If you try to encode an indexed array in PHP, you’ll fall flat on your face, my friend.

$myArray = array('Audi', 'Mercedes', 'VW');
echo json_encode($myArray); // ["Audi","Mercedes","VW"]

As you can see, trying to encode an indexed array in PHP by itself will just spit out another array. 😐 What if we try to encode other data structures. What can kind of results can we expect?

$associativeArray = array("Chunk Bytes" => true, "Awesome" => "Yes");
echo json_encode($associativeArray); // {"Chunk Bytes":true,"Awesome":"Yes"}

class Person {
    public $firstname = "Dilshan";
    protected $lastname = "Kelsen";
    private $blog = "Chunk Bytes";

$person = new Person();
echo json_encode($person); // {"firstname":"Dilshan"}

As seen in the example above, encoding an associative array will return a JSON string as expected. Nothing to worry about here.😀 Conversely, encoding an object works as you would expect it to… with one small caveat: protected and private properties are left out from the encoding!

Pay attention to multidimensional JSON objects

On the other hand, when you decode a JSON string, PHP will return by default a standard class as seen in the snippet of code below.

$jsonString = '{"Chunk Bytes":true,"Awesome":"Yes"}';
$result = json_decode($jsonString);

var_dump($result); // object(stdClass)#1 (2) { ["Chunk Bytes"]=> bool(true) ["Awesome"]=> string(3) "Yes" }

However, if you’d like to convert it into an associative array instead, simply add true as a second parameter to the function as follows: json_decode($jsonString, true);. Furthermore, for multidimensional JSON strings, you can limit 🛑 the depth of the decoding by indicating it as an additional parameter.

$jsonString = '{"Chunk Bytes":{"Awesome":{"Yes":true}}}';
$result = json_decode($jsonString, true, 2);

var_dump($result); // NULL

Consequently, the function returns NULL if the depth of the given JSON object is deeper than what has been indicated.

Did you find what you came for? Want me to cover something else? Let me know in the comments below! Share, if you liked this post!

Published inPHP

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *