简体   繁体   中英

How to properly escape Ruby hash to JSON for javascript JSON.parse?

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>

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM