繁体   English   中英

将ruby哈希转换为json对象

[英]converting ruby hash into json object

因此,我正在遍历一组数据并从中构建一个哈希值:

clean_response = Array.new
        response.each_with_index do |h, idx|
        clean_response <<
        {
                    :lat => h["location"]["latitude"],
                    :lg => h["location"]["longitude"],
                    :place => h["location"]["name"],
                    #This grabs the entire hash at "location" because we are wanting all of that data
                    :profile_picture => h["user"]["profile_picture"],
                    :hash_tags => h["tags"],
                    :username => h["user"]["username"],
                    :fullname => h["user"]["full_name"],
                    :created_time => (Time.at(h["created_time"].to_i)).to_s,
                    :image => h["images"]["low_resolution"]["url"] # we can replace this with whichever resolution.
        }
        end

返回散列数组,如下所示:

[{:lat=>40.7486382,
  :lg=>-73.9487686,
  :place=>"The Cliffs at LIC",
  :profile_picture=>"http://scontent.cdninstagram.com/hphotos-xaf1/t51.2885-19/s150x150/12104940_1653775014895036_286845624_a.jpg",
  :hash_tags=>["bouldering"],
  :username=>"denim_climber",
  :fullname=>"DenimClimber",
  :created_time=>2015-10-13 22:58:09 -0400,
  :image=>"https://scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s320x320/e35/11856571_1062082890510188_611068928_n.jpg"},
 {:lat=>40.7459602,
  :lg=>-73.9574966,
  :place=>"SHI",
  :profile_picture=>"http://scontent.cdninstagram.com/hphotos-xaf1/t51.2885-19/11348212_1453525204954535_631200718_a.jpg",
  :hash_tags=>["cousins", "suchafunmoment", "johnlennonstyle"],
  :username=>"xiomirb",
  :fullname=>"Xiomi",
  :created_time=>2015-10-13 22:57:21 -0400,
  :image=>"https://scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s320x320/e35/11375290_1688934151392424_2009781937_n.jpg"}]

我想将此数据转换为json,然后将其提供给特定的视图。 我该如何转换呢? 我尝试了.to_json方法,但是由于我的UI没有绑定到数据,它没有返回格式正确的方法。

您可以使用to_json将Ruby哈希转换为JSON:

require 'json'

your_hash.to_json # gives you a JSON object

但是,在您的情况下,数据是散列数组,而不是散列。 因此,您的to_json无法使用。

我不太确定您to_json ,但是一种可能性是遍历哈希数组,获取每个哈希,并使用to_json调用将其转换为JSON对象(如上所示),并构建一个新的JSON对象数组。 这样,您可以从哈希数组中构建一个JSON对象数组。

array_of_json = []
# loop through the array of hashes
clean_response.each do |hash|
  array_of_json << hash.to_json
end
array_of_json # array of JSON objects

如果“将其提供给特定视图”是指将其传递给.haml或.erb模板,则可以按原样传递哈希数组。 haml和erb都允许您遍历数组,如果需要还可以遍历哈希。

如果您想将json字符串传递给浏览器,则#to_json应该可以正常工作。 当您要优化发送的内容时,其他选项是jbuilder或oat,但是to_json应该很好地为您服务!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM