Reputation: 175
I just started using Rails for my web application's framework. Now I'm working on an API for a test project. I want the key of my API's JSON response to be camelcase instead of snakecase. How can I do that?
My JSON respond is something like this:
{"id":3,"name":"Bingo Gem", ..., "can_purchase":true,"shine":6,"created_at":"2014-07-31T06:34:37.917Z","updated_at":"2014-07-31T06:34:37.917Z","reviews":[]}
The response I expected:
{"id":3,"name":"Bingo Gem", ..., "canPurchase":true,"shine":6,"createdAt":"2014-07-31T06:34:37.917Z","updatedAt":"2014-07-31T06:34:37.917Z","reviews":[]}
Here's one of my controllers:
module Api
module V1
class PermataController < ApplicationController
respond_to :json
def index
respond_with Permatum.all, :include => [:reviews]
end
end
end
end
and routes.rb:
namespace :api, defaults: { format: 'json'} do
namespace :v1 do
resources :schedules
resources :permata
end
end
Upvotes: 2
Views: 1582
Reputation: 2901
In Rails, there is a method camelize
in String class. Use it:
"can_purchase".camelize(:lower) #=> "canPurchase"
"created_at".camelize(:lower) #=> "createdAt"
Upvotes: 3