【问题标题】:converting ruby hash into json object将 ruby​​ 哈希转换为 json 对象
【发布时间】:2015-10-14 03:24:59
【问题描述】:

所以我正在遍历一组数据并从中构建一个哈希:

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 没有绑定到数据。

【问题讨论】:

    标签: ruby-on-rails ruby json hash


    【解决方案1】:

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

    require 'json'
    
    your_hash.to_json # gives you a JSON object
    

    但是,在您的情况下,数据是散列数组,而不是散列。因此,您的 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
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2011-03-12
        • 2011-06-29
        • 1970-01-01
        • 2017-04-04
        • 1970-01-01
        • 1970-01-01
        • 2020-09-15
        • 1970-01-01
        • 2011-12-19
        相关资源
        最近更新 更多