Ruby 哈希到 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5419467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby hash to JavaScript
提问by newbie_86
I have a Ruby hash which is passed to a hidden field. How do I extract this hash into JavaScript arrays that I can work with? I need to access the key/value pairs in JavaScript.
我有一个传递给隐藏字段的 Ruby 哈希值。如何将此哈希提取到我可以使用的 JavaScript 数组中?我需要访问 JavaScript 中的键/值对。
采纳答案by Jakub Hampl
Use my_awesome_ruby_hash.to_json
and then you can simply either eval
it in js or use parseJSON
. You might need to require 'json'
(not in Rails).
使用my_awesome_ruby_hash.to_json
然后你可以简单地eval
在 js 中使用它或使用parseJSON
. 您可能需要require 'json'
(不是在 Rails 中)。
回答by Lane
Ruby code:
红宝石代码:
state = { 'Waiting' => { name: 'Waiting now', color: 'btn-default' },
'Trying' => { name: 'Trying now', color: 'btn-danger' },
'Answered' => { name: 'Answered now', color: 'btn-success' } }
javascript code:
javascript代码:
var state = JSON.parse('#{raw(state.to_json)}');