如何解析 JSON 字符串并打印特定元素?
How do I parse a JSON string and print a particular element?
我尝试使用 Ruby 从某些 JSON 获取值,但得到:
[]': no implicit conversion of String into Integer (TypeError)
from jsonpars.rb:61:in `<main>'
这是我用来解析和打印特定元素的代码。
你能告诉我如何打印特定值,如 screen_name
或 url
或 text
吗?
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,
}
}
您不应该使用 .first
,因为您已经获得了所需的哈希值。在这种情况下使用 .first
是以数组的形式从该散列中获取第一个键值对。
发生 TypeError 的原因是因为它认为您正在尝试使用字符串 'user'
而不是整数来调用该数组的索引。
只需使用:
print json['user']['screen_name'];
在第 61 行而不是
print json.first['user']['screen_name'];
我尝试使用 Ruby 从某些 JSON 获取值,但得到:
[]': no implicit conversion of String into Integer (TypeError)
from jsonpars.rb:61:in `<main>'
这是我用来解析和打印特定元素的代码。
你能告诉我如何打印特定值,如 screen_name
或 url
或 text
吗?
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,
}
}
您不应该使用 .first
,因为您已经获得了所需的哈希值。在这种情况下使用 .first
是以数组的形式从该散列中获取第一个键值对。
发生 TypeError 的原因是因为它认为您正在尝试使用字符串 'user'
而不是整数来调用该数组的索引。
只需使用:
print json['user']['screen_name'];
在第 61 行而不是
print json.first['user']['screen_name'];