Code Smart: JSON

For the next chapter on Composer, we're going to need a basic understanding of JSON. Trust me; it doesn't hurt to learn this stuff. JSON is used by a bunch of different technologies.

JSON stands for JavaScript Object Notation. It was named this way because JavaScript was the first language to take advantage of the format.

Essentially, JSON is a human readable method of storing arrays and objects with values as strings. It is used primarily for data transfer and is a lot less verbose than some of the other options such as XML.

Commonly, it is used when the front-end part of your application requires some data from the back-end without a page reload. This is commonly achieved using JavaScript with an AJAX or 'XHR' request.

Many software APIs also serve content using this file format. Twitter’s own is an excellent example of such an API.

Since version 5.2.0, PHP has been able to serialise objects and arrays to JSON. This is something I have personally abused a billion or so times and was a great addition to the language.

If you have been working with PHP for a while, you may have already used its serialize() method to represent a PHP object as a string. You are then able to use the unserialize() method to transform the string into a new instance containing the original value.

It’s what we will be using JSON for. However, the advantage is that JSON can be parsed by a variety of different languages, where serialize()d strings can only be parsed by PHP. The additional advantage is that we (as humans and pandas) can read JSON strings, but PHP serialised strings will look like garbage.

Enough back story. Let’s dive right in and have a look at some JSON.

JSON Syntax

{"name":"Lushui","species":"Panda","diet":"Green Things","age":7,"colours":["red","brown","white"]}

Yay! JSON! Okay. When I said it was readable to humans, I may have forgotten to mention something. By default, JSON is stored without any white space between its values. This might make it a little more difficult to read.

This is normally used to save on bandwidth when transferring the data. Without all the extra whitespace, the JSON string will be much shorter and thus be fewer bytes to transfer.

The good news is that JSON doesn’t care about whitespace or line breaks between its keys and values. Go wild! Throw all the white space you want in there to make it readable.

Sure, we could do this by hand (let’s not), but there are plenty of tools out there on the web to beautify JSON. I won’t choose one for you. Go hunting! You might even find extensions for your web browser to allow you to read JSON responses from web servers more easily. I highly recommend finding one of these!

Let’s add some whitespace to the JSON from before to make it easier to read. (Honestly, I did do this by hand. Don’t try this at home folks.)

{
    "name":         "Lushui",
    "species":      "Panda",
    "diet":         "Green Things",
    "age":          7,
    "colours":      ["red", "brown", "white"]
}

Aha! There we go. We now have a JSON string representing the red panda that lives on the cover of my books. Lushui safely guards your Laravel knowledge against prying eyes.

As you can see from the example, we have some key-value pairs. Within one of the key-value pairs, we have an array. If you have used some JavaScript before you may wonder what has changed here? In fact, let’s have a look at how this would be represented in JavaScript.

var lushui = {
    name:       'Lushui',
    species:    'Panda',
    diet:       'Green Things',
    age:        7,
    colours:    ['red', 'brown', 'white']
};

Hopefully, you will have spotted some similarities between the JavaScript and JSON snippets.

The JavaScript snippet is assigning an object literal to a variable, like this:

var lushui = { .. };

JSON is a data transfer format and not a language. It has no concept of variables. This is why you don’t need the assignment within the JSON snippet.

The method of representing an object literal is very similar. This is no coincidence! As I said before, JSON was originally invented for use with JavaScript.

In both JSON and JavaScript, objects are contained within { two curly braces } and consist of key-value pairs of data. In the JavaScript variant, the keys didn’t require quotes because they represent variables, but we know that JSON doesn’t have variables. This is fine since we can use strings as keys, and that’s what JSON does to work around this problem.

You may also have noticed that I used single quotes around the JavaScript values. This is a trap! That behaviour is perfectly acceptable with JavaScript, but JSON strings must be contained within double quotes. You must remember this, young padawan!

In both JavaScript and JSON, key-value pairs must be separated with a colon (:), and sets of key-value pairs must be separated by a comma (,).

JSON will support strings and numerical types. You can see that the value for Lushui’s age is set to an integer value of seven.

age: 7,

JSON will allow the following value types.

  • Double
  • Float
  • String
  • Boolean
  • Array
  • Object
  • Null

Numeric values are represented without quotes. Be careful when choosing whether to quote a value or not. For example, US zip codes consist of five numbers. However, if you were to omit the quotes from a zip code, then 07702 would act as an integer and be truncated to 7702. This has been a mistake that has taken many a life of a web-faring adventurer.

Booleans are represented by the words true and false, both without quotes much like PHP itself. As I said previously, string values are contained within double quotes and not single quotes.

The null value works in a similar way to PHP and is represented by the word null without quotes. This should be easy to remember!

We have seen objects. Much like the main JSON object itself, they are wrapped with curly braces and can contain all sorts of value types.

Arrays look very similar to their JavaScript counterpart.

// JavaScript
['red', 'brown', 'white']

["red", "brown", "white"]

T> You will notice that I didn’t add an inline comment for the JSON snippet in the above example. That’s because JSON doesn’t support commenting since it’s used for data transfer. Keep that in mind!

As you can see, the arrays for both are wrapped within [ square braces ], and contain a list of comma (,) separated values with no indexes. The only difference is that double quotes must be used for strings within JSON. Are you getting bored of me saying that yet?

As I mentioned above, the values that can be contained within JSON include both objects and arrays. The clever chaps amongst my readers (aka all of you) may have realised that JSON can support nested objects and arrays. Let’s have a look at that in action!

{
    "an_object": {
        "an_array_of_objects": [
            { "The": "secret" },
            { "is": "that" },
            { "I": "still" },
            { "love": "shoes!" }
        ]
    }
}

Okay. Take a deep breath. Here we have a JSON object containing an object containing an array of objects. This is perfectly fine, and will allow JSON to represent some complex data collections.

JSON and PHP

As mentioned previously since version 5.2.0 PHP has provided support for serialising and unserializing data to and from the JSON format. Let’s go ahead and have a look at that in action.

Serialise a PHP array to JSON

To serialise a PHP value we need only use the json_encode() method.

<?php

$truth = ['panda' => 'Awesome!'];
echo json_encode($truth);

The result of this snippet of code would be a JSON string containing the following value.

{"panda":"Awesome!"}

Great! That’s more like it. Let’s make sure that we can convert this data back into a format that can be understood by PHP.

Unserialise a PHP array from JSON

For this we will use the json_decode() method. I bet you didn’t see that one coming?

<?php

$truth = json_decode('{"panda":"Awesome!"}');
echo $truth['panda'];

Awesome! We go... wait. What?

Fatal error: Cannot use object of type stdClass as array in ...

You see, the json_decode() method doesn’t return our JSON as a PHP array; it uses a stdClass object to represent our data. Let’s instead access our object key as an object attribute.

<?php

$truth = json_decode('{"panda":"Awesome!"}');
echo $truth->panda;

// Awesome!

Great! That’s what we wanted. If we wanted an array instead, then PHP provides some ways to convert this object into one, but fortunately json_decode() has another trick up its sleeve!

If you provide true as the second parameter to the function, we will receive our PHP array exactly as expected. Thanks json_decode()!

<?php

$truth = json_decode('{"panda":"Awesome!”}', true);
echo $truth['panda'];

// Awesome!

Huzzah!

So you might be wondering why I just wrote a gigantic chapter on JSON within a Laravel book. Furthermore, you are probably asking why I’m choosing to answer this question at the end of the chapter!?

It’s just more fun that way.

In the next section, we will be taking a look at the package manager for PHP. When we start looking at Composer, you will understand why a knowledge of JSON is so important.

My books are available online for free to encourage learning. However, if you'd like for me to keep writing, then please consider buying a digital copy over at Leanpub.com.

It's available in PDF, ePub, and Kindle format, and contains a bunch of extras that you won't find on the site. I have a full-time job, and I write my books in my spare time. Please consider buying a copy so that I can continue to write new and exciting books!