2011-11-16 143 views
0

我试图将以下字符串转换为散列或json。将字符串解析为JSON /散列

我该如何在ruby中做到这一点?

[{"place":null,"coordinates":null,"in_reply_to_user_id":null,"in_reply_to_status_id":null, 
"favorited":false,"truncated":false,"created_at":"Wed Nov 16 08:00:46 +0000 2011","retweet_count":0,"in_reply_to_screen_name":null, 
"user":{"profile_background_image_url":"http:\/\/a1.twimg.com\/profile_background_images\/190989640\/afcx.jpg","protected":false, 
"statuses_count":23414,"profile_link_color":"FF0000"},"retweeted":false,"in_reply_to_status_id_str":null,"in_reply_to_user_id_str":null,"contributors":null,"geo":null}] 

我正在运行ruby1.8.7。

+0

注意,Rails有一个JSON库,但如果你使用Rails的我不知道。 –

回答

4

你看起来已经是JSON了,所以我假设你正在寻找一个Ruby Hash。如果是这样,那么这应该工作:

得到一个JSON库,我用gem install json_pure,这是一个本地的Ruby实现(有一个更快的,基于C的版本,但你不会注意到的区别,除非你的JSON字符串是非常大或你有很多)。

然后

require 'json' 
arr = JSON(your_json_string_here) 

注意,你给该字符串包含的东西,将映射到一个Ruby的Hash一个单元素数组。如果你只是想哈希:

the_hash = arr[0] # or maybe arr.first 

我得到这个:

{"coordinates"=>nil, "created_at"=>"Wed Nov 16 08:00:46 +0000 2011", 
"truncated"=>false, "favorited"=>false, "in_reply_to_user_id_str"=>nil, 
"contributors"=>nil, in_reply_to_status_id_str"=>nil, "retweet_count"=>0, 
"geo"=>nil, "retweeted"=>false, "in_reply_to_user_id"=>nil, 
"user"=>{"profile_link_color"=>"FF0000", "protected"=>false, 
"statuses_count"=>23414, 
"profile_background_image_url"=>"http://a1.twimg.com/profile_background_images/190989640/afcx.jpg"}, 
"in_reply_to_screen_name"=>nil, place"=>nil, "in_reply_to_status_id"=>nil}