0

I'm trying to embed a ruby hash into a json string that can be parsed by javascript JSON.parse.

I'm having escaping issues.

Ruby:

props = {sring: 'He said "hey"'}

HAML

:javascript
  const props = JSON.parse('#{props.to_json}');

Which renders as

<script>
  const props = JSON.parse('{"sring":"He said \"hey\""}');
</script>

Which throws the following error:

Uncaught SyntaxError: Expected ',' or '}' after property value in JSON at position 19
    at JSON.parse (<anonymous>)
    at (index):58:24

I've experiemented a bit and the following string is parseable by JSON.parse, but not sure how to produce it from an escape function:

<script>
  const props = JSON.parse('{"sring":"He said \\\"hey\\\""}');
</script>
mechnicov
  • 12,025
  • 4
  • 33
  • 56
pixelearth
  • 13,674
  • 10
  • 62
  • 110
  • Is there some reason why `const props = props.to_json` does not work? I cannot see any reason why you need to wrap this in single quotes or convert to JSON just to parse the JSON. – engineersmnky Oct 10 '22 at 19:08
  • 1
    This is basically what I ended up doing (technically `const props = #{raw(props.to_json)}`. I'm not sure exactly where I got the JSON.parse idea, but I think from looking at another library. – pixelearth Oct 10 '22 at 19:16

2 Answers2

0

Yes, strange behavior, but you always can use DOM for this purpose like this

- props = {string: 'He said "hey"'}

div[data-props=props.to_json id="props"]

javascript:
  const props = JSON.parse(document.getElementById("props").dataset.props)
mechnicov
  • 12,025
  • 4
  • 33
  • 56
0

Call on Hash Objects, Not String Objects

You're misunderstanding where to apply #to_json. You're currently applying it to a String object, when you should be serializing the entire Hash. For example:

require 'json'

props = {string: 'He said "hey"'}.to_json
JSON.parse props
#=> {"string"=>"He said \"hey\""}

In other words, convert your Hash to JSON, not the String. A String by itself will not properly serialize to or from JavaScript Object Notation, which needs to be in a key/value format.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199