Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Serialize Model to JSON with camelize

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?

like image 588
nixterrimus Avatar asked Jun 02 '11 00:06

nixterrimus


2 Answers

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

like image 102
Pete Avatar answered Sep 24 '22 20:09

Pete


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"}}

Source: https://github.com/rails/rails/blob/4-2-stable/activesupport/lib/active_support/core_ext/hash/keys.rb#L88

like image 31
jbarr Avatar answered Sep 25 '22 20:09

jbarr