2 ruby hash json ruby-on-rails
因此,我正在迭代一组数据并从中构建哈希:
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
Run Code Online (Sandbox Code Playgroud)
它返回一个哈希数组,如下所示:
[{: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"}]
Run Code Online (Sandbox Code Playgroud)
我想将此数据转换为 json,然后将其提供给特定视图。我该如何转换这个?我尝试了该.to_json方法,但它没有返回格式良好的方法,因为我的 UI 未绑定到数据。
您可以使用以下方法将 Ruby 哈希转换为 JSON to_json:
require 'json'
your_hash.to_json # gives you a JSON object
Run Code Online (Sandbox Code Playgroud)
但是,在您的情况下,数据是哈希数组,但不是哈希。所以,你的方法to_json是行不通的。
我不太确定你想如何做到这一点,但一种可能性是循环遍历哈希数组,获取每个哈希并使用调用将其转换为 JSON 对象to_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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7671 次 |
| 最近记录: |