Difference between as_json and to_json method in Ruby
Solution 1:
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:
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