rails

Output View as JSON in Rails 5

A memo on how to output VIEW as JSON in Rails 5. Uses respond_to and format.json. Normally in Rails, the text written in VIEW.erb has template HTML added to it, but you can specify formats like JSON or XML to make it usable as a REST API, etc.

Shou Arisaka
1 min read
Nov 17, 2025

A memo on how to output VIEW as JSON in Rails 5. Uses respond_to and format.json.

Normally in Rails, the text written in VIEW.erb has template HTML added to it, but you can specify formats like JSON or XML to make it usable as a REST API, etc.

Like this:

respond_to do |format|
            format.html

                @json=%({"origin":#{@origin_addresses.to_json},"dest":#{@destination_addresses.to_json},"km":#{@km.to_json}})

            format.json {render :json => @json}
end

respond_to is optional, but… Let me explain.

When you use respond_to, when ./page is accessed normally, show.html.erb (assuming this action method is “show”) is referenced, and when ./page.json explicitly requests json with an extension, it references the contents of the @json variable specified in format.json and outputs it as is.

So… if you’re only using it as a dedicated API, you don’t really need to use respond_to. Just in case.

to_json escapes variables as JSON. There’s something similar like escape_Javascript(?), but it seems better to use this one.

Share this article

Shou Arisaka Nov 17, 2025

🔗 Copy Links