So, I’m converting a reasonably complex object to JSON format using object.as_json in ruby in my view, and then parsing it on the client side using JSON.parse() in javascript to deserialise the object into something usable. However, the output from as_json seems to be using single quote marks encoded as " as opposed to the double quotes required for JSON structure. Any suggestions what I am doing wrong with as_json?
So, I’m converting a reasonably complex object to JSON format using object.as_json in ruby
Share
Ah, worked out what was going on: it was in fact a combination of two different issues:
Firstly, the quotes were being automatically encoded by rails (to prevent XSS and similar). This can be escaped by using the
html_safemethod or therawfunction (this can introduce XSS vulnerabilities, though, so use with care).Secondly, I was using
as_jsoninstead ofto_json. Converting an ActiveSupport object to JSON in rails requires two seperate operations: rendering the object into a structure which can be serialised to JSON, and then actually serialising the object.to_jsondoes both, butas_jsononly does the first. This explains why I was getting=>in my output.