How to extract data from Tumblr API (JSON)?

MeltingDog picture MeltingDog · Jan 25, 2013 · Viewed 15.1k times · Source

I have set up a Tumblr account and registered my application to authenticate it.

Tumblr Documentation: http://www.tumblr.com/docs/en/api/v2

I understand the API outputs JSON like this:

{
   "meta": {
      "status": 200,
      "msg": "OK"
   },
   "response": {
      "blog": {
         "title": "David's Log",
         "posts": 3456,
         "name": "david",
         "url": "http:\/\/david.tumblr.com\/",
         "updated": 1308953007,
         "description": "<p><strong>Mr. Karp<\/strong> is tall and skinny, with
            unflinching blue eyes a mop of brown hair.\r\n
         "ask": true,
         "ask_anon": false,
         "likes": 12345
      }
   }
}

Thats fine, but the documentation ends there. I have no idea how to get this information and display it on my site.

I thought the way you would get it would be something like:

$.ajax({
    url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/info?api-key=myapikey",
    dataType: 'jsonp',
    success: function(results){
        console.log(results);
    }
});

But this does nothing.

Can anyone help me out? Thanks

Answer

Workman picture Workman · Jan 25, 2013

results is now the object you can use to reference the JSON structure. When you console.log the results object, it should appear in the Javascript developer console where you can explore the object tree.

The response object

So when your success callback receives the response, the following should be available to you:

results.meta.status => 200

results.meta.msg => "OK"

results.response.title => "David's Log"

results.response.posts => 3456

results.response.name => "david"

results.response.url => "http://david.tumblr.com/"

results.response.updated => 1308953007

results.response.description => "<p><strong>Mr. Karp</strong>.."

results.response.ask => true

results.response.ask_anon => false

results.response.likes => 12345


Writing to the page

If you actually want to see something written to your page you'll need to use a function that modifies the DOM such as document.write, or, since you're using Jquery, $("#myDivId").html(results.response.title);

Try this:

  • Add <div id="myDivId"></div> somewhere in the of your page, and
  • Add $("#myDivId").html(results.response.title); in your success callback function

$.ajax({
    url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/info?api_key=myapikey",
    dataType: 'jsonp',
    success: function(results){
        // Logs to your javascript console.
        console.log(results); 
        // writes the title to a div with the Id "myDivId" (ie. <div id="myDivId"></div>)
        $("#myDivId").html(results.response.title); 
    }
});