Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between as_json and to_json method in Ruby

What's the difference between the two methods as_json and to_json. Are they same? If not what's the difference between them?

like image 975
Gowtham Avatar asked Jul 11 '16 08:07

Gowtham


People also ask

What does to_json do in Ruby?

Returns a JSON string representing the hash.

What is as_json?

as_json is used to create the structure of the JSON as a Hash, and the rendering of that hash into a JSON string is left up to ActiveSupport::json. encode. You should never use to_json to create a representation, only to consume the representation.”


2 Answers

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} 
like image 157
Shin Kim Avatar answered Sep 29 '22 10:09

Shin Kim


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

like image 23
oreoluwa Avatar answered Sep 29 '22 10:09

oreoluwa