Search code examples
rubyjsonhashtumblropen-uri

Pulling posts from tumblr with ruby


I am trying to figure out how to pull posts from a specific Tumblr account with ruby. My end goal would be to have a hash with the post number => text. I am only looking for the text and each post number.

I tried the following (for demo.tumblr.com):

require 'open-uri'
require 'json'

jtest = JSON.load(open("http://api.tumblr.com/v2/blog/demo.tumblr.com/posts/text?api_key=fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4&notes_info=true&filter=text"))
puts jtest

which gives me, I'm only going to put a snippet of it:

{"meta"=>{"status"=>200, "msg"=>"OK"}, "response"=>{"blog"=>{"title"=>"Demo", "name"=>"demo", "posts"=>7, "url"=>"http://demo.tumblr.com/", "updated"=>1269024321, "description"=>"Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.", "is_nsfw"=>false, "ask"=>false, "ask_page_title"=>"Ask me anything", "ask_anon"=>false, "share_likes"=>false}, "posts"=>[{"blog_name"=>"demo", "id"=>459009076, "post_url"=>"http://demo.tumblr.com/post/459009076/lorem-ipsum-dolor-sit-amet-consectetuer", "slug"=>"lorem-ipsum-dolor-sit-amet-consectetuer", "type"=>"text", "date"=>"2006-10-01 04:00:00 GMT", "timestamp"=>1159675200, "state"=>"published", "format"=>"html", "reblog_key"=>"uHt0TEhP", "tags"=>[], "short_url"=>"http://tmblr.co/Zg4ybyRM_mq", "highlighted"=>[], "note_count"=>5793, "title"=>"", "body"=>"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam nisi lorem, pulvinar id, commodo feugiat, vehicula et, mauris. Aliquam mattis porta urna. Maecenas dui neque, rhoncus sed, vehicula vitae, auctor at, nisi. Aenean id massa ut lacus molestie porta. Curabitur sit amet quam id libero suscipit venenatis.", "notes"=>[{"timestamp"=>"1429905090", "blog_name"=>"hdpreview2", "blog_url"=>"http://hdpreview2.tumblr.com/", "post_id"=>"117273527904", "type"=>"reblog"}

it goes on for a while but I am just not sure how to drill down into that. It seems jtest is actually a hash but with only two items, the first is

{meta => {"status"=>200, "msg"=>"OK"}}

and the second is:

{response => the rest of that....

I am probably in over my head but I cannot wrap my head around how to just get text posts out of a tumblr blog via ruby.


Solution

  • What you're really asking is how to access values in a hash. I'm sure there's plenty of precedent here on SO.

    But to get you started, here are some examples:

    jtest["meta"]["status"] #=> 200
    jtest["response"]["blog"]["title"] #=> "Demo"
    

    At any point you can inspect the output. I like using pp to get nicer formatting.