What's the difference between the two methods as_json
and to_json
. Are they same? If not what's the difference between them?
Returns a JSON string representing the hash.
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.”
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}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With