Drupal offers two functions for encoding and decoding JSON. To encode an array into JSON usedrupal_json_encode()
and to decode a JSON object into an array use the - can you guess it? -drupal_json_decode()
function.
Encoding JSON
First, let’s look at encoding an array into JSON. Take this array for example:
$array = array('Boat', 'Car', 'Ship', 'Building');
If we were to encode the above array into JSON, you will get ["Boat","Car","Ship","Building"]
returned. Here is a code example:
$array = array('Boat', 'Car', 'Ship', 'Building');
$output = drupal_json_encode($array);
// $output will be ["Boat","Car","Ship","Building"]
Decoding JSON
Now let's look at decoding a JSON object. If you were to running the following code:
$json = '["Boat","Car","Ship","Building"]';
return drupal_json_decode($json);
The drupal_json_decode()
function will return an array.
Pulling In JSON Objects
The next example I want to demonstrate is how to pull in a Twitter account using Twitter's GET users/show REST API.
First, we’ll need to get the JSON object and for this we’ll use the drupal_http_request() function:
$request = drupal_http_request('https://api.twitter.com/1/users/show.json?screen_name=TwitterAPI&include_entities=true');
Within the $request
variable, there will be a data property $request->data
. This stores the JSON object.
The only thing left to do is decode the data property to get access to all the information.
$request = drupal_http_request('https://api.twitter.com/1/users/show.json?screen_name=TwitterAPI&include_entities=true');
return drupal_json_decode($request->data);
JSON Endpoints
The last item I want to demonstrate is how to create a JSON endpoint for content on a Drupal site. For example, if you navigate to example.com/node/1/json the website will output a JSON version of the content. This will show you how to output a full JSON page using the drupal_json_output() function.
First we must implement a menu item using the hook_menu. The menu item path needs to be "node/%node/json". For more details on how to use hook_menu check out the API documentation.
/**
- Implements hook_menu().
*/
function ww_json_example_menu() {
$items['node/%node/json'] = array(
'page callback' => 'ww_json_example_endpoint',
'page arguments' => array(1),
'access arguments' => array('access content'),
);
return $items;
}
Create a "page callback" function for the menu item. Also, make sure that you add a $node variable to the function signature. For this example, the page callback is "ww_json_example_endpoint". Finally, we pass the $node object through to the drupal_json_output() function. If you go to node/1/json you should just see outputted JSON code.
function ww_json_example_endpoint($node) {
drupal_json_output($node);
}