Rails as_json incorrectly encodes JSON.parse

So, I convert a fairly complex object to JSON format using object.as_json in ruby ​​in my view, and then parse it on the client side using JSON.parse() in javascript to deserialize the object into something useful. However, the output from as_json seems to use single quotation marks encoded as " , unlike the double quotes required for the JSON structure. Any suggestions what I am doing wrong with as_json?

+4
source share
1 answer

And, I found out what was going on: in fact, it was a combination of two different problems:

First, quotation marks were automatically encoded with rails (to prevent XSS and similar). This can be escaped using the html_safe method or the raw function (this can lead to XSS vulnerabilities, however, use them with caution).

Secondly, I used as_json instead of to_json . Converting an ActiveSupport object in JSON to rails requires two separate operations: rendering the object into a structure that can be serialized to JSON, and then actually serializes the object. to_json does both, but as_json only does the first. This explains why I was getting => in my release.

+5
source

All Articles