Drupal - How to read JSON from external URL and display in a block?

For the most basic solution, you would need to:

  • Create a custom module;
  • Implement hook_block_info and hook_block_view to define your block (see block_example.module for examples);
  • When generating the block content, use drupal_http_request to retrieve the json data from your URL and process the return value as needed.

A more complex version of your custom module could for instance involve implementing hook_block_configure to make the URL configurable from the UI, using theme functions to generate the HTML output, and caching/storage of the return value.

A completely different approach, which may or may not be appropiate in your case, would be to use the Feeds module to retrieve the JSON and store the data as nodes, and use the Views module to generate a block listing those nodes.


Maybe too simple of an approach, but if all you truly want to do is display JSON data (no need to store it), then I'd add a new block as "Full HTML" and then add some JQuery.

To embed an HTML snippet it would be:

<script type="text/javascript">
(function ($) {
$(document).ready(function(){
  $('#remoteFeed').load('http://example.com/path/to/page #some-div-id');
});
})(jQuery);
</script><div id="remoteFeed"></div>

The method would be similar for JSON, only you'd have to do some formatting of the return that would be custom to your application.

Here's a working example pulled from JQuery.getJSON documentation customized ever so slightly to work inside a Drupal Block:

<script type="text/javascript">
(function ($) {
$(document).ready(function(){
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "awesome",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){
      $("<img/>").attr("src", item.media.m).appendTo("#flickr-images");
      if ( i == 3 ) return false;
    });
  });
});
})(jQuery);
</script>
<div id="flickr-images"></div>

Tags:

7