Difference between as_json and to_json method in Ruby
Ruby on-RailsRubyRuby on-Rails Problem Overview
What's the difference between the two methods as_json
and to_json
. Are they same? If not what's the difference between them?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
to_json
returns String.
as_json
returns Hash with String keys.
> { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json
"{\"name\":\"Konata Izumi\",\"age\":16,\"1\":2}"
> { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.as_json
{"name"=>"Konata Izumi", "age"=>16, "1"=>2}
Solution 2 - Ruby on-Rails
as_json
returns a hash representation of your model object, while to_json
returns a json object.
Note: Internally, when you call the to_json
method on your model/serializer, as_json is first called.
You can read more here