Reputation:
I need to serialize a model to json and have all of the keys be camelized. I see that there's an option in to_xml to allow camel case. I can't seem to coerce the json serialization into giving me back a camelized hash. Is this something that's possible in rails?
Upvotes: 8
Views: 8567
Reputation: 8541
For my case,I was required to customize some key names.
Usage
puts self.camelize_array(array:Post.all.to_a,conditions:{id: "_id",post_type: "type"})
Implementation
def self.camelize_array(array:,conditions: {})
final = JSON.parse array.to_json
final.each do |a|
a.transform_keys! do |key|
if conditions.keys.include? key.to_sym
key = conditions[key.to_sym]
else
key.camelize(:lower)
end
end
end
final.to_json
end
Upvotes: 1
Reputation: 464
If you are using rails, skip the added dependency and use Hash#deep_transform_keys
. It has the added benefit of also camelizing nested keys (handy if you are doing something like user.as_json(includes: :my_associated_model)
):
h = {"first_name" => "Rob", "mailing_address" => {"zip_code" => "10004"}}
h.deep_transform_keys { |k| k.camelize(:lower) }
=> {"firstName"=>"Rob", "mailingAddress"=>{"zipCode"=>"10004"}}
Upvotes: 11
Reputation: 2246
I had a similar issue. After a bit of research I wrapped the as_json ActiveModel method with a helper that would camelize Hash keys. Then I would include the module in the relevant model(s):
# lib/camel_json.rb
module CamelJson
def as_json(options)
camelize_keys(super(options))
end
private
def camelize_keys(hash)
values = hash.map do |key, value|
[key.camelize(:lower), value]
end
Hash[values]
end
end
# app/models/post.rb
require 'camel_json'
class Post < ActiveRecord::Base
include CamelJson
end
This worked really well for our situation, which was relatively simplistic. However if you're using JBuilder, apparently there's a configuration to set camel case as the default: https://stackoverflow.com/a/23803997/251500
Upvotes: 11
Reputation: 1136
Working with RABL Renderer directly, you can pass an inline template, instead of fetching it from a file:
Rabl::Renderer.new("\nattributes :name, :description", object).render
The \n
character is necessary at the beginning of the string.
Upvotes: 0
Reputation: 7887
It seems weird to me to use camelized attribute names in Rails, let alone json. I would stick to the conventions and use underscored variable names.
However, have a look at this gem: RABL. It should be able to help you out.
Upvotes: -1