Rails - Serializing a JSON Model with camelize

I need to serialize a model for json and all keys will be camels. I see that there is an option in to_xml to allow the camel case. I can't seem to force json serialization to return the camel to the hash. Is this possible on rails?

+6
source share
4 answers

It seems strange to me to use camel attribute names in Rails, not to mention json. I would like to stick to conventions and use the names of redefined variables.

However, look at this gem: RABL . He should be able to help you.

0
source

I had a similar problem. After a little research, I wrapped the as_json ActiveModel method with a helper that would haveh the hash keys. Then I would include the module in the appropriate 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 very well for our situation, which was relatively simplified. However, if you are using JBuilder, apparently there is a setting to set the camel case to default: fooobar.com/questions/889595 / ...

+9
source

If you use rails, skip the added dependency and use Hash#deep_transform_keys . It has the added benefit of having camel-embedded 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

+4
source

Working with RABL Renderer directly, you can transfer the built-in template, and not extract it from the file:

 Rabl::Renderer.new("\nattributes :name, :description", object).render 

The \n character is needed at the beginning of a line.

0
source

Source: https://habr.com/ru/post/889590/


All Articles