Crashdesk
Crashdesk

Reputation: 665

How to parse tumblr JSON feed

I need to get the regular title and regular body from this JSON feed. I have tried various methods with little success. Anyone have a solution?

http://clintonbeattie.tumblr.com/bio/json

Thanks, C

Upvotes: 1

Views: 5148

Answers (2)

James Sumners
James Sumners

Reputation: 14777

From their API docs:

JSON output

By using /api/read/json instead of /api/read when calling the Read API, the output will be sent as JSON assigned to a Javascript variable named tumblr_api_read.

That is not JSON, or even JSONP. They are returning literal JavaScript. Thus, you have to follow their documentation and do:

<script type="text/javascript" src="http://clintonbeattie.tumblr.com/api/read/json"></script>

This will create a global variable named tumblr_api_read (i.e. window.tumblr_api_read) that is an object literal.

Since you are using jQuery, you could do the following:

$.getScript("http://clintonbeattie.tumblr.com/api/read/json", function(script, textStatus, jqXHR) {
  console.log(window.tumblr_api_read.tumblelog.title);
});

It's amazing to me that these guys can link to json.org in their documentation, yet screw it up this badly.

Upvotes: 2

Matt
Matt

Reputation: 75317

That is not JSON, thats a weird-ish take on JSONP.

If you add a <script /> tag with the src set to http://clintonbeattie.tumblr.com/bio/json, a global variable tumblr_api_read will point to an object with the response information;

var tumblr_api_read = {
    "tumblelog": {
        "title": "First Title",
        "description": "",
        "name": "clintonbeattie",
        "timezone": "US\/Eastern",
        "cname": false,
        "feeds": []
    },
    "posts": [{
        "id": null,
        "url": "",
        "url-with-slug": "",
        "type": "regular",
        "date-gmt": " GMT",
        "date": "Wed, 31 Dec 1969 19:00:00",
        "bookmarklet": null,
        "mobile": null,
        "feed-item": "",
        "from-feed-id": 0,
        "unix-timestamp": 1333622193,
        "format": "html",
        "reblog-key": "TmN3ujDJ",
        "slug": "",
        "regular-title": "",
        "regular-body": ""
    }]
};

Therefore do something like this;

<script src="http://clintonbeattie.tumblr.com/bio/json"></script>
<script>
    // Use tumblr_api_read.

    alert(tumblr_api_read.tumblelog.title); // Shows "First Title"

    for (var i=0;i<tumblr_api_read.posts.length;i++) {
        var thisPost = tumblr_api_read.posts[i];

        alert("This post was created at " + thisPost.date);
    }
</script>

Upvotes: 4

Related Questions