1

My multi-word strings aren't being interpreted correctly in the DOM. How can I ensure JSON integrity from server to HTML with multi-word strings?

In the Rails controller, I store a JSON object in a variable. That object is correctly formatted when I check in the server logs. That variable is then passed to a data attribute in the view via erb. However, the generated HTML is incorrect.

# in the controller
@hash = {'subhash' => {'single' => 'word', 'double' => 'two words' } }.to_json
puts @hash.inspect

# output in the server log
=> "{\"subhash\":{\"single\":\"word\",\"double\":\"two words\"}}"

# view.html.erb
<section data-hash=<%= @hash %> ></section>

# generated html, 'double' value is incorrect
<section data-hash="{"subhash":{"single":"word","double":"two" words&quot;}}>

# complete data value is not obtainable in the console
> $('section').data().hash
< "{"subhash":{"single":"word","double":"two"

Update

# adding html_safe does not help
{"subhash" => {"single" => "word", "double" => "two words" } }.to_json.html_safe

# results in
"{"subhash":{"single":"word","double":"two" words"}}
mu is too short
  • 426,620
  • 70
  • 833
  • 800
steel
  • 11,883
  • 7
  • 72
  • 109

1 Answers1

3

If you push past the browser's interpretation of your "HTML" and look directly at the source you should see something like this:

<section data-hash={&quot;subhash&quot;:{&quot;single&quot;:&quot;word&quot;,&quot;double&quot;:&quot;two words&quot;}}>

At least that's what I get with Rails4.2. That also gives me the same results that you're seeing when I look at the HTML in a DOM inspector.

The browser is seeing that as:

<section data-hash={"subhash":{"single":"word","double":"two words"}}>

and trying to make sense of it as HTML but that doesn't make sense as HTML so the browser just gets confused.

If you add the outer quotes yourself:

<section data-hash="<%= @hash %>">
                   ^            ^

then you'll get this in the HTML:

<section data-hash="{&quot;subhash&quot;:{&quot;single&quot;:&quot;word&quot;,&quot;double&quot;:&quot;two words&quot;}}">

and the quotes will be interpreted correctly as the &quot;s will be seen as HTML encoded content for the data-hash attribute rather than a strange looking attempt at an HTML attribute.

mu is too short
  • 426,620
  • 70
  • 833
  • 800