Output JSON instead of HTML
suggest changeclass UsersController < ApplicationController
def index
hashmap_or_array = [{ name: "foo", email: "foo@example.org" }]
respond_to do |format|
format.html { render html: "Hello World".html_safe }
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
/usersor/users.html, it renders an HTML page with the contentHello World.render html:requires a safe string in Rails 5+. - If you visit
/users.json, it will display a JSON object containing:
[
{
"name": "foo",
"email": "foo@example.org"
}
]
Omit the format.html branch if the action should respond only to JSON. The example above uses render html:, not render inline:.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents