我有一个哈希表,大概长这个样子:
Track_list = {:track1=>{:url=>"https://open.spotify.com/track/2Oehrcv4Kov0SuIgWyQY9e", :name=>"Demons"},
:track2=>{:url=>"https://open.spotify.com/track/0z8yrlXSjnI29Rv30RssNI", :name=>"Shots - Broiler Remix"},
:track3=>{:url=>"https://open.spotify.com/track/6Ep6BzIOB9tz3P4sWqiiAB", :name=>"Radioactive"},
:track4=>{:url=>"https://open.spotify.com/track/3I05foFixB2sSZvV5Ppty8", :name=>"Blank Space/Stand By Me - Medley / Live From Spotify London"},
:track5=>{:url=>"https://open.spotify.com/track/4G8gkOterJn0Ywt6uhqbhp", :name=>"Radioactive"}}
我正在尝试将该哈希转换为JSON格式,以便在我的JS文件中使用。以下是我在控制器中所做的:
@tl = track_list.as_json
# and it produces a result like this:
# {"track1"=>{"url"=>"https://open.spotify.com/track /2Oehrcv4Kov0SuIgWyQY9e", "name"=>"Demons"},
# "track2"=>{"url"=>"https://open.spotify.com/track/0z8yrlXSjnI29Rv30RssNI", "name"=>"Shots - Broiler Remix"},
# "track3"=>{"url"=>"https://open.spotify.com/track/6Ep6BzIOB9tz3P4sWqiiAB", "name"=>"Radioactive"},
# "track4"=>{"url"=>"https://open.spotify.com/track/3I05foFixB2sSZvV5Ppty8", "name"=>"Blank Space/Stand By Me - Medley / Live From Spotify London"},
# "track5"=>{"url"=>"https://open.spotify.com/track/4G8gkOterJn0Ywt6uhqbhp", "name"=>"Radioactive"}}
然而,当我打开我的 JS 文件并尝试输出文件时,我得到了如下结果:
console.log("<%= @tl %>");
"{"track1":{"url":"https://open.spotify.com/track/2Oehrcv4Kov0SuIgWyQY9e","name":"Demons"},"track2":{"url":"https://open.spotify.com/track/0z8yrlXSjnI29Rv30RssNI","name":"Shots - Broiler Remix"},"track3":{"url":"https://open.spotify.com/track/6Ep6BzIOB9tz3P4sWqiiAB","name":"Radioactive"},"track4":{"url":"https://open.spotify.com/track/3I05foFixB2sSZvV5Ppty8","name":"Blank Space/Stand By Me - Medley / Live From Spotify London"},"track5":{"url":"https://open.spotify.com/track/4G8gkOterJn0Ywt6uhqbhp","name":"Radioactive"}}"
当我尝试执行以下操作时:
console.log(JSON.parse("<%= @tl %>");
它不能工作。我也尝试在@tl
前面放置j
,但是它给了我一个错误,说哈希不能与 gsub
一起使用。
另外,当我尝试这样做时:
@track_list = JSON.generate(@tl) # from above
I get this:
"{\"track1\":{\"url\":\"https://open.spotify.com/track/2Oehrcv4Kov0SuIgWyQY9e\",\"name\":\"Demons\"},\"track2\":{\"url\":\"https://open.spotify.com/track/0z8yrlXSjnI29Rv30RssNI\",\"name\":\"Shots - Broiler Remix\"},\"track3\":{\"url\":\"https://open.spotify.com/track/6Ep6BzIOB9tz3P4sWqiiAB\",\"name\":\"Radioactive\"},\"track4\":{\"url\":\"https://open.spotify.com/track/3I05foFixB2sSZvV5Ppty8\",\"name\":\"Blank Space/Stand By Me - Medley / Live From Spotify London\"},\"track5\":{\"url\":\"https://open.spotify.com/track/4G8gkOterJn0Ywt6uhqbhp\",\"name\":\"Radioactive\"}}"
所以它实际上正确地转义了所有内容...我不知道为什么当我在我的JS文件中使用相同的变量时,它不会转义引号或其他任何内容。
谢谢!
html_safe
时它才能正常工作。 - K M Rakibul Islam