Category Archives: PHP

My name is JSON, Part 1

So here it is, my first post. And while I may have been slightly distracted by the ´╗┐rise of our robotic overlords, it didn’t take me that long to think of a starter for 10. As a mobile and web developer there are always certain things that may not seem important at first, but start to take a greater importance when you realise just how useful it can be, even for mundane things like encapsulating data for easy transfer.

So I’m beginning with Javascript Object Notation, or JSON for short. JSON is one of the most widely-used methods of holding data in a structured format, XML being its main rival. This was a topic originally thrust onto me during a University project in 2010, and while seeming daunting at the time turned out to be fairly straightforward. Before I explain how this data can be handled in PHP and Java, let’s take a look at some JSON-encoded data.

So what does JSON look like? Something like this:

{
    "forename" : "Michael",
    "surname" : "Dodd",
    "age" : 23,
    "breaks" : [34, 66, 12, 35, 22, 73, 94, 147],
    "match" : {
        "frames_won" : 5,
        "frames_lost" : 3
    }
}

This example is my performance in a snooker match (I wish!). Similar to PHP, this data structure can be seen as an array with named keys. Each key can contain:

  • A simple value such as a string or integer.
  • An array of simple values, denoted by square brackets [ ].
  • A child JSON object, denoted by curly braces { }.

With the ability to structure data in such a fashion, it is easy to map the data in a JSON object to the data structure in your application. One point to note when creating these structures, however, is to make sure that the final entry in each object does not have a comma at the end of it as this may cause problems with some parsers.

In the next few posts, I will explain how JSON data can be used with PHP and Java (with an Android flavour), but for now check out some of the many potential uses of JSON data with the Guardian Open Platform API.