Ruby on Rails:如何解析可能包含或不包含数组的JSON字符串

时间:2015-02-03 22:55:19

标签: ruby-on-rails json

我在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"}

我的问题 - 如何解析" id"从JSON结果中我不知道数组是否存在?

1 个答案:

答案 0 :(得分:0)

...单

> 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"]