Getting Started with JSON

Preface

You send data in a JSON format between different parts of your system. API results are often returned in JSON format, for example. JSON is a lightweight format which makes for easy reading if you’re even the least bit familiar with JavaScript.

What does it look like?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
    "movie": {
        "name": "drive",
        "year": "2011",
        "people": {
            "actors": [
                {
                    "name": "ryan gosling"
                },
                {
                    "name": "cary mulligan"
                },
                {
                    "name": "bryan cranston"
                }
            ]
        }
    }
}

There we go, that’s JSON my friend. Now, when it looks like this, it’s not the prettiest thing in the world but you’ll rarely be working with raw JSON. You might be using PHP’s json_decode() function or JavaScript’s JSON.parse() to bring it into a more readable (we all prefer reading array outputs and console logged objects, right?) format for us to manipulate with our application code.

Using PHP

PHP has a couple of functions to handle JSON; json_decode() and json_encode(). The latter will take an array as a parameter and output valid JSON, for example:

1
2
3
4
5
6
7
8
9
10
11
$array = array(
    'name' => 'ben',
    'age' => 23,
    'skills' => array(
        'php', 'css', 'javascript'
    )
);

$json = json_encode($array);

print_r($json);

Will produce:

1
{"name":"ben","age":23,"skills":["php","css","javascript"]}

Similarly, json_decode() works like so:

1
2
3
$json = '{"name":"ben","age":23,"skills":["php","css","javascript"]}';

print_r(json_decode($json));

and output:

1
stdClass Object ( [name] => ben [age] => 23 [skills] => Array ( [0] => php [1] => css [2] => javascript ) )

The nice thing about json_decode() is that it takes an optional second parameter to return the JSON as an array, instead of an object, like so:

1
2
3
$json = '{"name":"ben","age":23,"skills":["php","css","javascript"]}';

print_r(json_decode($json, true));

And output:

1
Array ( [name] => ben [age] => 23 [skills] => Array ( [0] => php [1] => css [2] => javascript ) )

Much better. (I prefer working with arrays, but hey, that’s just me)

Using JavaScript

Ok, so JSON works nicely with JavaScript because browsers natively support JSON, which makes it a breeze to integrate it into your application.

Two methods are primarily used with JavaScript and JSON; JSON.parse() and JSON.stringify(). The first will break down a JSON string into an Object and the latter will create a JSON string from an Object.

JSON.parse() works like so:

1
2
3
var jsonString = '{"name":"ben","age":23,"skills":["php","css","javascript"]}';
var json = JSON.parse(jsonString);
console.log(json);

will produce:

1
2
3
4
5
6
7
Object
    age: 23
    name: "ben"
    skills: Array[3]
        0: "php"
        1: "css"
        2: "javascript"

Similarly, JSON.stringify works like this:

1
2
3
4
5
6
7
8
9
10
var data = {
    name: 'ben',
    age: 23,
    skills: [
        'php', 'css', 'javascript'                
    ]
}
    
var json = JSON.stringify(data);
console.log(json);

Will output:

1
{"name":"ben","age":23,"skills":["php","css","javascript"]} 

Pretty nifty, huh?

Throw it all Together

Ok, so now we see the real benefit of JSON.

We have some data that we want to send between our backend logic and our frontend UI, you don’t want to send the user to a different page so just use JSON.

First, let’s gear ourself up with some data in the PHP (I’m using Michael’s excellent guide to cURL for this code):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$username = (empty($_REQUEST['username'])) ? FALSE : $_REQUEST['username'];

if($username !== FALSE){
    $url = 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name='.$username.'&count=5&include_entities=1&include_rts=1';
    // Get cURL resource
    $curl = curl_init();
    // Set some options
    curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => $url
    ));
    // Send the request & save response to $resp
    $resp = curl_exec($curl);
    // Close request to clear up some resources
    curl_close($curl);
    if($resp){
        echo $resp;
    }
} else {
    echo 'failed';
}

This code accesses REQUEST data sent by the JavaScript and stores it in a $username variable, passing it into the cURL to be processed.

We then echo the response from the cURL back to the JavaScript.

We’re going to be using jQuery (just because it makes using AJAX & JSON super simple). So we set up a few HTML elements:

1
2
3
4
5
    <input type="text" id="username">
    <button id="grab">Grab!</button>
    <div id="result">

    </div>

Now we can use our jQuery to send the value of the input to the PHP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$(document).ready(function(){
    var user = $('#username');
    var result = $('#result');
    $('#grab').click(function(){
        if(user.val() !== ''){
            var config = {
                username: user.val()
            }
            
            $.ajax({
              url: 'json_grab.php',
              dataType: "json",
              data: config,
              success: function(json){
                for(x in json){
                    result.append(json[x].text);
                }
              },
            });
        }
    });
});

As you can see, our returned data is parsed using jQuery’s own JSON methods and we can manipulate it like a normal object.

There we have a quick tweet grabber using PHP & jQuery with JSON in a few lines.

Ben’s final words…

Whatever data format you choose to work with is cool, JSON is just my preferred method as I work with JavaScript a lot and have unnecessary hatred for XML. If any confusion from this arises or you simply you have a eureka moment, I would love to hear about it @benhowdle.

Invaluable resources