2

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=&gt;\&quot;2\&quot;, :tries=&gt;\&quot;3\&quot;}

doing j @edges.to_json results in

 \&quot;{:source=&gt;\\\&quot;2\\\&quot;, :target=&gt;\\\&quot;3\\\&quot;} }\&quot;

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?

2
  • 2
    try @options[0].to_json Commented Mar 19, 2013 at 15:32
  • 2
    The content is being scaped, try @options.to_json.html_safe Commented Mar 19, 2013 at 15:34

2 Answers 2

4

dont use j. try

myFunc(<%= @options.to_json %>)
Sign up to request clarification or add additional context in comments.

Comments

0

You may use gsub to remove those unwanted chars:

@options[0].to_json.gsub(/\"/,'')
# => "{source:2,tries:3}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.