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?
1 Answer
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_safe method or the raw function (this can introduce XSS vulnerabilities, though, so use with care).
Secondly, I was using as_json instead of to_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_json does both, but as_json only does the first. This explains why I was getting => in my output.
{ "id"=>303, "name"=>" test sequence", "privacy"=>0, "updated_at"=>Mon, 03 Dec 2012 21:51:39 UTC +00:00, "user_id"=>1}