如何解析JSON字符串并打印特定元素?

时间:2015-04-15 19:43:05

标签: ruby json api parsing twitter

我尝试使用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,
   }

}

1 个答案:

答案 0 :(得分:1)

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

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

只需使用:

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

在第61行而不是

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