Gianluca Ghettini
Gianluca Ghettini

Reputation: 11628

Ruby on Rails: output JSON data from array

I have a webpage in which a javascript code requests JSON data from a remote URL using XMLHTTPRequest(). The URL is served by a Ruby on Rails app. I tried to print an hardcoded JSON string from a test view but it get wrapped around HTML tags (html, head, body etc..etc..) so it's not reconized as a valid JSON string from the javascript code. What I want is to output a raw JSON string straight from a Ruby object.

Upvotes: 0

Views: 1338

Answers (1)

Vlad Khomich
Vlad Khomich

Reputation: 5880

You should either use respond_to block (in case your action handles multiple formats) or explicitly state that you want to render json (easier in case your action only handles json):

class SomeController < ApplicationController
  def some_action
    @data        = Data.find(1)
    @string_json = '{ "key": "value" }'

    render json: @data # render json: @string_json also works
  end
end

EDIT:

If you're trying to only render a json string on a page, you should disable a common layout for your action:

class SomeController < ApplicationController
  layout 'application', :except => :some_action

  def some_action
    @json_string = ' .... '
  end
end

some_action.erb:

<%= @json_string %>

Upvotes: 2

Related Questions