【问题标题】:Tumblr API with Ruby带有 Ruby 的 Tumblr API
【发布时间】:2015-10-18 06:04:53
【问题描述】:

我是 ruby​​ 的新手,目前正在构建一个需要从 Tumblr 博客中提取的 rails 应用程序。我在这里阅读了几个问题、在线教程和 Tumblr 的 API 文档,两周后我被困住了。

https://www.tumblr.com/docs/en/api/v2

我在控制器中使用 Tumblr 拨打电话

require 'json'
require 'tumblr_client'
client = Tumblr::Client.new :consumer_key => 'consumerkey'
@post = client.posts 'crossfitinterchange.tumblr.com', :type => 'text', :limit => 1, :filter => 'html'

然后返回(短 sn-p)

{"blog"=>{"title"=>"Today's Workout", "name"=>"crossfitinterchange", "posts"=>118, "url"=>"http://crossfitinterchange.tumblr.com/", "updated"=>1444971275, "description"=>"", "is_nsfw"=>false, "ask"=>false, "ask_page_title"=>"Ask me anything", "ask_anon"=>false, "share_likes"=>true, "likes"=>0}, "posts"=>[{"blog_name"=>"crossfitinterchange", "id"=>131266609424, "post_url"=>"http://crossfitinterchange.tumblr.com/post/131266609424/friday-oct-16th-wod", "slug"=>"friday-oct-16th-wod", "type"=>"text", "date"=>"2015-10-16 04:54:35 GMT", "timestamp"=>1444971275, "state"=>"published", "format"=>"html", "reblog_key"=>"OWmgAbMO", "tags"=>[], "short_url"=>"http://tmblr.co/ZE0_uk1wG6O4G", "recommended_source"=>nil, "recommended_color"=>nil, "highlighted"=>[], "note_count"=>0, "title"=>"Friday Oct 16th WOD", "body"=>"<p>[STRENGTH]</p>\n\n<p>5 x 3 Push Press to find 3RM</p>\n\n<p>* complete 5 ring rows after each set</p>\n\n<p><br/>\n[CONDITIONING]</p>\n\n<p>7 mins EMOM:</p>\n\n<p>5 sit ups<br/>\nME Thrusters (115/80#) for duration of round</p>\n\n<p><br/>\n- REST 2 mins -</p>\n\n<p><br/>\n2 mins AMRAP Box Jump Overs (24/20&quot;)</p>\n\n<p><br/>\nScore is total Thrusters + Box Jump Overs</p>", ...

在我看来我有

<% @post.each do |p| %>
<%= p.title %>
<%= p.body %>
<% end %>

我收到标题和正文未定义的错误。 我正在通过 API 返回 JSON,现在如何获取帖子的标题和正文?

【问题讨论】:

    标签: ruby-on-rails ruby api tumblr


    【解决方案1】:

    您的 @post 对象包含 JSON 数据。因此,您无需循环访问,即无需在该对象上使用 .each

    要从@post JSON 对象中获取titlebody,您应该这样做:

    title = @post['blog']['title']
    body = @post['blog']['body']
    

    【讨论】:

    • 感谢您的快速回复!我在上面输入了一个 TypeError no implicit conversion of String into Integer。之前需要解析JSON吗?
    • 我以为 @post 已经是 JSON 了?如果不是,那么可以,使用.to_json 调用将其设为json 对象,然后尝试我上面的建议。它应该工作。如果没有,请告诉我!
    • 应该按照API文档。我读过的其他一些问题说它是 JSONP 或某种形式的 JSONP。
    • 您可以检查程序中的对象类型:puts @post.class 如果没有,则通过:@post = @post.to_json 将其设为 json。然后:@post['blog']['title']
    • 当我在 irb 中执行 puts @post.class 时,响应为 Hash =&gt; nil
    猜你喜欢
    • 2023-03-21
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多