Ruby on Rails ActionController Output JSON instead of HTML


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

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

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": ""

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