rails添加到json响应

时间:2011-07-09 14:36:20

标签: ruby-on-rails json ruby-on-rails-3

我以前做过这个,但不记得现在怎么做了。

从foursquare获得一个json响应,其中包括:

"hereNow"=>{"count"=>1, "groups"=>[{"type"=>"friends", "name"=>"friends here", "count"=>0, "items"=>[]}, ...]}

我用@place(这是位置信息)回复,但想把名字和图片作为json传递给我的视图。

想法就像@place['hereNow'] << response['venue']['hereNow']一样,将其包含在我的render :json => @place

1 个答案:

答案 0 :(得分:1)

关键是:收到的jsonstring,因此您无法直接使用它。

这里有两个步骤:

  • 将收到的json转换为Hash

  • 轻松添加您想要的任何内容Hash

  • hash转换回json

有很多例子here

简而言之:

j = ActiveSupport::JSON
hash = { :color => ["red", "green", "jellow"], :date => Time.now }
json_string    = j.encode hash
recreated_hash = j.decode json_string