as_json vs to_json
I’ve been working on a basic Rails/JS application that requires us to pass data from the DB into an Array in JS, which taught me something new about the deep world of Rails.
When rendering JSON I’ve always been taught to set my controllers up as follows :
Nothing complicated, we create our method, and render it to_json, explicitly stating what will get passed around.
While working on this project I got introduced to the following
A subtle difference when rendering as_json instead of to_json.
So What is the difference?
Well it turns out to_json is a wrapper that includes our as_json option.
“Anytime to_json is called on an object, as_json is invoked to create the data structure, and then that hash is encoded as a JSON string using ActiveSupport::json.encode. This happens for all types: Object, Numeric, Date, String, etc”
Sounds great, but this becomes problematic when JSON for instance, is returned as a small portion of a larger structure. There is a possibility that JSON characters might escape
“ Now the creation of the json is separate from the rendering of the 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.”