Laravel 4 Primer: JSON

Welcome to one of the Primer topics within Code Bright.

Hey this chapter wasn’t in Code Happy!?

As a true fan of Code Happy I just can’t put anything past you! Well done loyal reader!

You see, Laravel 4 uses a number of new technologies regularly. These technologies can easily be taught on their own and parallel to the framework. With this in mind, I thought it might be best to open with a chapter about this new tech to ‘prime’ you for your learning experience.

Experienced web developers may have already come across these technologies, or have already been using them. You are welcome to skip any of the primer chapters if you want to. I won’t be upset. No really... go on. You don’t need me anymore..

Let’s jump right in to our first primer to talk about JSON.

What is JSON?

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 normally achieved using JavaScript with an AJAX request.

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

Since version 5.2.0, PHP has been able to serialize 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. This method has been around for a while, and is used to serialize a PHP value or object to a string. You are then able to use the unserialize() to transform the string into a new instance containing the original value.

It’s roughly what we will be using JSON for. However, the advantage is that JSON can be parsed by a variety of different languages, where as 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 serialized 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, so 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 which might make it a little more difficult to read.

This is normally to save on bandwidth when transferring the data. Without all the extra whitespace, the JSON string will be much shorter and thus be less 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 do this by hand. You see, 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 from prying eyes.

As you can see from the example, we have a number of key-value pairs. Within one of the key value pairs we have an array. In honesty, if you have used some JavaScript before you may wonder what’s 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 snipped is assigning an object literal to a variable, like this:

var lushui = { .. };

Well 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 consists of key-value pairs of data. In the JavaScript variant the keys didn’t require quotes because they represent variables, but we just heard that JSON doesn’t have variables. This is fine since we can use strings as keys, and that’s exactly 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 with 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 before, 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.

Arrays once again look very similar to their JavaScript counterpart.

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

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

*Note 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. Once again 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 I mentioned earlier, since version 5.2.0 PHP has provided support for serializing and unserializing data to and from the JSON format. Let’s go ahead and have a look at that in action.

Serialize a PHP array to JSON

To serialize a PHP value we need only use the json_encode() method. Like this:

<?php

$truth = array('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 exactly what we wanted. Let’s make sure that we can convert this data back into a format that can be understood by PHP.

Unserialize a PHP array from a JSON string

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. Instead 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 then PHP provides a number of 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? Further more, 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 chapter we will be taking a look at a new package manager for PHP. When we start looking at composer you will understand why a knowledge of JSON is so important.