Reputation: 18597
I'm trying to render a ruby hash to a json string in haml. (the !
tells haml not to escape the output)
! { :name => "Paul" }.as_json
I expect this output
{ "name":"Paul" }
but I get a hash rocket instead of a colon
{ "name"=>"Paul" }
How do I make haml or as_json
output a colon instead of a hash rocket for the property/value separator?
Upvotes: 2
Views: 3812
Reputation: 3379
as_json
is essentially a method that allows you to specify how an object is represented in JSON. It doesn't actually go as far as returning a JSON encoded string. to_json
is needed for that.
The reason for this is that you might want to decide which fields your model returns when JSON encoded (say, removing the password from the User model), but by using to_json
, you no longer have the ability to nest that within another JSON object, as it's become an encoded and escaped string.
to_json
will call as_json
, and will encode the return value.
Referenced from: http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/
Upvotes: 7