Search code examples
rubyjsonopen-uri

How to handle a json file return by the server with ruby?


I have a json file return by a web radio

require 'open-uri'
rquiire 'json'
songlist=open('http://douban.fm/j/mine/playlist?type=n&channel=0')
##this will return a json file:
##{"r":0,"song" [{"album":"\/subject\/25863639\/","picture":"http:\/\/img5.douban.com\/mpic\/s27256956.jpg","ssid":"7656","artist":"Carousel Kings","url":"http:\/\/mr3.douban.com\/201404122019\/660a1b4494a255e0333dfdc9ffadcf08\/view\/song\/small\/p2055547.mp3","company":"Not On Label","title":"Silence","rating_avg":3.73866,"length":194,"subtype":"","public_time":"2014","sid":"2055547","aid":"25863639","sha256":"ebf027adfaf9882118456941a774eeb509c29c4c278f55f587ba2faaa858a49d","kbps":"64","albumtitle":"Unity","like":false}]

I want to get the information like this song[0]['url'], song[0]['title'],song[0]['album']and using smplayer in terminal to play the song by pointed by url.

How can i do that with ruby?

Thanks.


Solution

  • I would use JSON.parse as below

    require 'open-uri'
    require 'json'
    
    songlist = open('http://douban.fm/j/mine/playlist?type=n&channel=0').read
    parsed_songlist = JSON.parse(songlist)
    parsed_songlist["song"][0]["url"] #=> "http:\/\/mr3.douban.com\/201404122019\/660a1b4494a255e0333dfdc9ffadcf08\/view\/song\/small\/p2055547.mp3"
    parsed_songlist["song"][0]["title"] #=> "Silence"