Home > other >  Rails: How to convert hash of array of objects to json
Rails: How to convert hash of array of objects to json

Time:10-16

I'm a java and Js developer, so I'm completetly new to rails and ruby. In one of my project I'm using rails to consume an api and return in back to js. I'm converting the api response to a model in ruby.

Now, it's in format of {KEY1=>[{array of objects(my model)}], KEY2=>[{array of objects(my model)}]}

Also the keys to model is in snake_case. My requirement is to loop through this and convert this into JSON with camel case keys.

Api response after converting to model: { KEY1=>[{@person_name:"abc", @person_id="123"}],KEY2:[{@personName:"bca", @person_id="231"}] }

Desired output: { KEY1:[{personName:"abc", personId:"123"}],KEY2:[{personName:"bca",personId:"231"}] }

I tried using .map and .transform_values till now, but don't know where I'm doing wrong.

Any help is appreciated.

CodePudding user response:

You can add the following to your ApplicationRecord class:

class ApplicationRecord < ActiveRecord::Base
  def serializable_hash(options = {})
    hash = super
    return hash unless options[:camelize]

    hash.deep_transform_keys { |key| key.to_s.camelize(options[:camelize]) }
  end
end

This will allow you to call to_json(camelize: :lower) on pretty much any object:

{
  KEY1: Person.where(...),
  KEY2: Person.where(...),
}.to_json(camelize: :lower)

To automatically serialize the whole collection

CodePudding user response:

You can do something like this:

{ 
  KEY1: Person.where(...).select(:name, :id).map { |p| Hash[p.serializable_hash.map { |key, value| ["#{p.model_name.name.downcase}#{key.capitalize}", value] }] }, 
  KEY2: Person.where(...).select(:name, :id).map { |p| Hash[p.serializable_hash.map { |key, value| ["#{p.model_name.name.downcase}#{key.capitalize}", value] }] }
}.to_json
  • Related