【问题标题】:Twitter API implementing "trending"Twitter API 实现“趋势”
【发布时间】:2014-09-17 15:54:47
【问题描述】:

我正在尝试使用 Twitter API 列出热门话题。在调用我的函数并分配给“X”(然后打印“X”)后,我返回(以 JSON 格式解析)如下所示:

puts X

{"trends"=>[{"name"=>"blah blah", "query" =>"blah blah" and a bunch more info...
            {"name"=>"blah2 blah2", "query"=>"blah blah" and a bunch more...
            {"name"=>"blah3 blah3", and so on and so forth.}]}

我可以通过调用更接近我想要的输出

X.each do |T|
  puts T["trends"]
end

我可以让它像这样打印每一行:

{"name"=>"blah blah", "query" =>"blah blah" and a bunch more information
{"name"=>"blah2 blah2", "query"=>"blah blah" and a bunch more...
{"name"=>"blah3 blah3", and so on and so forth.}

如何让我的代码仅打印热门主题的名称?我在想这将是类似于

X.each do |T|
  puts T["trends"]["name"]
end

但这不起作用。我怎样才能让它只显示

blah  blah
blah2 blah2
blah3 blah3

根据迭戈 当我调用以下命令时,我得到了从字符串到整数的无转换错误。

X["trends"].each do |T|
    puts T["name"]
end

当我调用 X.inspect 时,我只会得到我放在问题顶部的内容,并在趋势周围添加了一组 []。

[{"trends"=>[{"name"=>"blah blah", "query" =>"blah blah" and a bunch more info...
            {"name"=>"blah2 blah2", "query"=>"blah blah" and a bunch more...
            {"name"=>"blah3 blah3", and so on and so forth.}]}]

我想通了。

X.each do |trend|
    trend["trends"].each do |topic|
        puts topic["name"]
    end
end

【问题讨论】:

  • 你能发布你检查该块内的 T 变量时得到的结果吗?试试puts T.inspect
  • 嗯...实际上似乎我得到的输出与打印 X 相同。在 X 上调用检查似乎会在所有内容周围添加一个 [] 括号,但简单地打印 X 会得到与调用 T.inspect
  • 我想通了,并为我的问题添加了答案。感谢迭戈的帮助。我试图支持你,但它说我的声誉太低了。不过,我将您标记为正确答案,因为它确实让我弄清楚了。
  • 好了,我给了你几票。快乐的堆栈溢出:)

标签: ruby api twitter


【解决方案1】:

你必须遍历'trends':

response = {"trends"=>[{"name"=>"blah blah", "query" =>"blah blah" and a bunch more information
            {"name"=>"blah2 blah2", "query"=>"blah blah" and a bunch more...
            {"name"=>"blah3 blah3", and so on and so forth.}]}

response['trends'].each do |trend|
  trend['name'] # do what you want with this
end

或者获取所有名字的数组:

response['trends'].map { |t| t['name'] }
# => ["blah blah", "blah2 blah2", "blah3 blah3"]

【讨论】:

  • 当我尝试 X["trends"].each 做 |T| T["name"] end 我得到 '[]': no iplicit conversion of String into Integer (TypeError)
  • 似乎您正在使用的数据与您在问题中发布的数据不匹配。无论您拥有包含“趋势”键(我的回答中为response)的任何变量,都对其调用检查并将其发布到您的问题中
  • 好的。我试图在评论中添加它,但代码显示不正确。我会把它添加到我的问题中。
猜你喜欢
  • 2016-03-29
  • 2016-12-16
  • 2017-03-11
  • 2011-03-11
  • 2014-06-06
  • 1970-01-01
  • 1970-01-01
  • 2013-05-08
  • 2023-04-01
相关资源
最近更新 更多