【问题标题】:How do I parse a JSON string and print a particular element?如何解析 JSON 字符串并打印特定元素?
【发布时间】:2015-06-21 22:55:48
【问题描述】:

我尝试使用 Ruby 从一些 JSON 中获取值,但得到了:

[]': no implicit conversion of String into Integer (TypeError)
    from jsonpars.rb:61:in `<main>'

这是我用于解析和打印特定元素的代码。 你能告诉我如何打印screen_nameurltext等特定值吗?

json = JSON.parse(response.body)

#json['user'].each do |alerts|
  # do whatever you want with these...
print json.first['user']['screen_name'];
#end

这是 JSON:

[
  {
    "metadata"=>{
      "iso_language_code"=>"en",
      "result_type"=>"recent"
    },
    "created_at"=>"Wed Apr 15 19:02:27 +0000 2015",
    "id"=>588417116358848512,
    "id_str"=>"588417116358848512",
    "text"=>"@BTS_twt i love India.arie too. My favourite is 'This Too Shall Pass' ????",
    "source"=>"<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
    "truncated"=>false,
    "in_reply_to_status_id"=>588412513093431296,
    "in_reply_to_status_id_str"=>"588412513093431296",
    "in_reply_to_user_id"=>335141638,
   }

}

【问题讨论】:

  • 代码看起来不错。你能告诉我第 61 行是什么吗?
  • 你好@Surya,下面是打印json的代码 json['statuses']['user'].each do |alerts| # 用这些做任何你想做的事... 第 61 行 >>print json.first['statuses']['user']['screen_name'];结束
  • 欢迎来到 Stack Overflow。与其给我们整个 JSON 字符串,不如将其减少到演示您所看到的问题所需的 bare 最小值。再多的东西,当我们浏览大量不必要的信息时,您会浪费空间和时间。
  • @theTinMan 对不起,我编辑了我的代码,我能够得到正确的解决方案。谢谢

标签: ruby json api parsing twitter


【解决方案1】:

您不应该使用.first,因为您已经获得了所需的哈希值。在这种情况下使用.first 会以数组的形式从该哈希中获取第一个键值对。

发生 TypeError 的原因是因为它认为您正在尝试使用字符串 'user' 而不是整数来调用该数组的索引。

只需使用:

print json['user']['screen_name'];

在第 61 行而不是

print json.first['user']['screen_name'];

【讨论】:

    猜你喜欢
    • 2019-10-26
    • 1970-01-01
    • 2021-02-08
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    相关资源
    最近更新 更多