Ruby on Rails ActionController Output JSON instead of HTML


Example

class UsersController < ApplicationController
  def index
    hashmap_or_array = [{ name: "foo", email: "foo@example.org" }]

    respond_to do |format|
      format.html { render html: "Hello World" }
      format.json { render json: hashmap_or_array }
    end
  end
end

In addition you will need the route:

resources :users, only: [:index]

This will respond in two different ways to requests on /users:

  • If you visit /users or /users.html, it will show an html page with the content Hello World
  • If you visit /users.json, it will display a JSON object containing:
[
  {
    "name": "foo",
    "email": "foo@example.org"
  }
]

You can omit format.html { render inline: "Hello World" } if you want to make sure that your route will answer only to JSON requests.