[英]How to get the length of an Array which may contain a single element in Rails?
[英]Ruby on Rails: how to parse a JSON string that may or may not contain an array
我在Rails中查詢歌曲數據庫。 如果歌曲出現在多個專輯中,則結果為數組。 如果該歌曲僅出現在一張專輯中,則沒有數組。 以下是結果片段:
結果數組:
"title"=>"Kokomo Blues",
"artist_name"=>"Mississippi Fred McDowell",
"tracks"=>
[{"album_type"=>"other",
"id"=>"TRGBEVE12EFD5C030F"},
{"album_type"=>"other",
"id"=>"TRAJQGU12EFD5C02FB"}]
單一結果:
"title"=>"Most Things Haven't Worked Out",
"artist_name"=>"Junior Kimbrough",
"tracks"=>
{"album_type"=>"other",
"id"=>"TRGBEVE12EFD5C030F"}
我的問題-當我不知道是否存在數組時,如何從JSON結果中解析“ id”?
單...
> h = {}
> h['tracks'] = {"album_type"=>"other","id"=>"TRGBEVE12EFD5C030F"}
=> {"album_type"=>"other", "id"=>"TRGBEVE12EFD5C030F"}
> [h['tracks']].flatten.map{|e| e['id']}
=> ["TRGBEVE12EFD5C030F"]
多...
> h = {}
> h['tracks'] = [{"album_type"=>"other", "id"=>"TRGBEVE12EFD5C030F"},
{"album_type"=>"other", "id"=>"TRAJQGU12EFD5C02FB"}]
=> [{"album_type"=>"other", "id"=>"TRGBEVE12EFD5C030F"},
{"album_type"=>"other", "id"=>"TRAJQGU12EFD5C02FB"}]
> [h['tracks']].flatten.map{|e| e['id']}
=> ["TRGBEVE12EFD5C030F", "TRAJQGU12EFD5C02FB"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.