I have a hash in ruby which holds options which I want to input for a javascript function
my hash is (as it prints in irb)
@options = [{:source=>"2", :tries=>"3"}]
my javascript function accepts options like
myFunc({source: num, tries: num})
So if in a js.erb file I do
myFunc(<%=j @options %>)
It would result in
{:source=>\"2\", :tries=>\"3\"}
doing j @edges.to_json
results in
\"{:source=>\\\"2\\\", :target=>\\\"3\\\"} }\"
doing j @edges.to_json.html_safe
results in
\"{:source=>\\\"2\\\", :target=>\\\"3\\\"}\"
Is there way to make it output a more javascript friendly hash?
dont use j
. try
myFunc(<%= @options.to_json %>)
You may use gsub
to remove those unwanted chars:
@options[0].to_json.gsub(/\"/,'')
# => "{source:2,tries:3}"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.