/ / RubyハッシュをJSONオブジェクトに変換 - Ruby-on-Rails、Ruby、JSON、ハッシュ

rubyハッシュをjsonオブジェクトに変換する - ruby​​-on-rails、ruby、json、hash

それで私はデータのセットを反復処理し、それからハッシュを構築しています:

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はデータにバインドしていないので、整形されたものを返しません。

回答:

回答№1は4

あなたはRubyハッシュをJSONに変換することができます。 to_json

require "json"

your_hash.to_json # gives you a JSON object

しかし、あなたの場合、データはハッシュの配列ですがハッシュではありません。だから、あなたの to_json 動作しません。

これをどのように実行したいかはよくわかりませんが、1つの可能性はハッシュの配列をループ処理し、各ハッシュを取得してそれを使用して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

回答№2の場合は0

「特定の見解に奉仕する」によってあなたが合格を意味するそれを.hamlまたは.erbテンプレートに渡すと、ハッシュの配列をそのまま渡すことができます。 hamlとerbの両方とも、あなたが望むなら配列さえも、そしてハッシュさえも繰り返すことを可能にします。

ブラウザにjson文字列を渡したいという場合は、#to_jsonを使用してください。あなたが送られるものを洗練させたいとき他のオプションはjbuilderかoatです、しかしto_jsonはあなたによく役立つでしょう!