Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails render json object with camelCase

I have the following controller code in a simple Rails API:

class Api::V1::AccountsController < ApplicationController
  def index
    render json: Account.all
  end

  def show
    begin
      render json: Account.includes(:cash_flows).find(params[:id]), include: :cash_flows
    rescue ActiveRecord::RecordNotFound => e
      head :not_found
    end
  end
end

The problem with this is that, the generated json have the format:

{
  id:2,
  name: 'Simple account',
  cash_flows: [
    {
      id: 1,
      amount: 34.3,
      description: 'simple description'
    },
    {
      id: 2,
      amount: 1.12,
      description: 'other description'
    }
  ]
}

I need that my generated json is camelCase('cashFlows' instead of 'cash_flows')

Thanks in advance!!!

like image 306
Augusto Pedraza Avatar asked May 21 '14 21:05

Augusto Pedraza


1 Answers

Following the recommended by @TomHert, I used JBuilder and the available config:

Keys can be auto formatted using key_format!, this can be used to convert keynames from the standard ruby_format to camelCase:

json.key_format! camelize: :lower
json.first_name 'David'

# => { "firstName": "David" }

You can set this globally with the class method key_format (from inside your environment.rb for example):

Jbuilder.key_format camelize: :lower

Thanks!!!

like image 173
Augusto Pedraza Avatar answered Oct 26 '22 07:10

Augusto Pedraza