Search code examples
ruby-on-railsjsonactive-model-serializers

Creating a list in json format


I want to display a "pretty" format of JSON api. I am using Active Model Serializers for most part. I learned that I can "prettify" my JSON display using JSON.pretty_generate() method.

I have tested it using a dummy data and it worked on browser:

def index
 #@users = User.all
 my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
 render json: JSON.pretty_generate(my_object)
end

localhost:

#=> {
  "array": [
    1,
    2,
    3,
    {
      "sample": "hash"
    }
  ],
  "foo": "bar"
}

My goal is to display a list of user information on index. Right now it does not have the indentation and newline... well, it does not look pretty:

User controller:

def index
     @users = User.all     
     render json: @users, each_serializer: UserSerializer, adapter: :json
UserSerializer)
   end

localhost:

{"users":[{"id":1,"username":"Iggy1","items":[{"id":1,"list_id":1,"name":"Wash dishes","completed":true},{"id":7,"list_id":1,"name":"Finish this assignment","completed":false}],"lists":[{"id":1,"name":"Important!","user_id":1,"permission":"private"},{"id":8,"name":"Bloc's obligatory list number two","user_id":1,"permission":"private"},{"id":14,"name":"Mandatory list one","user_id":1,"permission":"private"},{"id":15,"name":null,"use...

After much trial and error, I figured out that I need to have @users to be a list of json. Proof - when I run this:

User Controller:

def index
  @users = User.all
  render json: JSON.pretty_generate(@users), each_serializer: UserSerializer
end

localhost (shows error msg)

#=> only generation of JSON objects or arrays allowed

How can I apply JSON.pretty_generate() on User.all on user controller index?


Solution

  • Convert hash to json:

    JSON.pretty_generate(@users.to_json)