Difference between as_json and to_json method in Ruby

Ruby on-RailsRuby

Ruby 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGowthamView Question on Stackoverflow
Solution 1 - Ruby on-RailsShin KimView Answer on Stackoverflow
Solution 2 - Ruby on-RailsoreoluwaView Answer on Stackoverflow