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>
CodePudding user response:
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)
CodePudding user response:
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.