3

This my controller:

      def show
        @result = {"data"=>{"8"=>{"typeA"=>{"tier"=>[1,2],"message"=>"message"},"typeB"=>"sto"}}}
        respond_to do |format|
          format.js
        end
      end

So in show.js.erb I want to be able to create a JS object data that is @result['data']. But it's really not working... The closest I can seem to get is a string representation, but then JSON.parse fails to convert it to a JS object because all the characters have been encoded:

  console.log("<%= @result['data'] %>")
  var data = JSON.parse("<%= @result['data'] %>") 
  console.log(data)

ACTUAL OUTPUT

  > {&quot;8&quot;:{&quot;typeA&quot;:{&quot;message&quot;:&quot;message&quot;,&quot;tier&quot;:[1,2]},&quot;typeB&quot;:&quot;sto&quot;}}

  > Uncaught SYntaxError: Unexpected token & in JSON at position 1

DESIRED OUTPUT (for second console.log)

  > {"8":{"typeA":{"tier":[1,2],"message":"message"},"typeB":"sto"}}

Note I tried to do @result.to_json, this didn't help

2 Answers 2

3

Unless you use the raw view helper, Rails will automatically escape tags.

This should do the trick:

  var data = <%= raw(@result.to_json) %>;
  console.log(data);
  console.log(typeof data);

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried

@result.to_json

or j or escape_javascript helpers?

var data = JSON.parse("<%= j @result['data'] %>")

1 Comment

yes, unfortunately I get the same output with j

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.