4

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?

3
  • Could you post the output of object.as_json? Maybe when your object is returning, your keys may be a combination of strings and symbols. Commented Jan 23, 2013 at 6:28
  • sure: you get ouput like { "id"=>303, "name"=>" test sequence", "privacy"=>0, "updated_at"=>Mon, 03 Dec 2012 21:51:39 UTC +00:00, "user_id"=>1} Commented Jan 23, 2013 at 18:58
  • +1 That's nice. And respect for finding solution and share it. I am new in Rails, but I am finding the lack of help by other rails developer very disappointed. Commented Jun 18, 2013 at 19:58

1 Answer 1

5

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 =&gt in my output.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.