4

I am using pretty_generate in my controller, but I am getting the following error

'only generation of JSON objects or arrays allowed'

@celebrities = Celebrity.includes(:category)    
respond_to do |format|
  format.json { render json: JSON.pretty_generate(@celebrities.to_json(:include =>{:category => {:only => [:category]} })) }
end

I am not sure why I am getting this error

saravana
  • 311
  • 4
  • 14
  • Step through it in the console, eg do `@celebrities.to_json(:include =>{:category => {:only => [:category]} })`, store the result in a variable, call `JSON.pretty_generate` on it etc. – Max Williams Sep 07 '15 at 13:23
  • @MaxWilliams Same error, do I need to add require json somewhere – saravana Sep 07 '15 at 13:30
  • Possibly, try `require 'json'` – Max Williams Sep 07 '15 at 13:55
  • possible duplicate of [How can I "Pretty" format my JSON output in Ruby on Rails?](http://stackoverflow.com/questions/86653/how-can-i-pretty-format-my-json-output-in-ruby-on-rails) – zwippie Sep 07 '15 at 14:04

1 Answers1

3

As the error suggest, only generation of JSON objects or arrays allowed. I guess you should try this.

@celebrities = Celebrity.includes(:category)    
respond_to do |format|
  format.json { render json: JSON.pretty_generate(JSON.parse(@celebrities.to_json(:include =>{:category => {:only => [:category]} })))}
end
Amit Badheka
  • 2,677
  • 4
  • 19
  • 29