Sunday 15 February 2015

json - What is the best way to convert all controller params from camelCase to snake_case in Rails? -


As you already know, the JSON naming convention advocates the use of the ventspace and for the serial parameter names snake_case Advocates use. / P>

What is the best way to convert all configuration parameters into a trans controller in snake_case? From:

  {...} "firstname": "John", "Last name": "Smith", "More info": {"Food type ": 2," Size of food ": 4, ...}}   

To do this:

  {..." first_name ": "John", "last_name": "Smith", "more_info": {"food_type": 2, "food_size": 4, ...}}   

thanks

When you have finished the steps snake_case

For example, a passwordConfirmation is a JSON request param code> in a controller parameter [ : Password_confirmation]

will be used as config / initializers / json_param_key_transform.rb . This file is only going to change the parameter parsing behavior for JSON requests (in the JSON requests the request header should be the header Content-type: application / json .)

Find your Rail version And select the appropriate section below (find your rail version in Gemfile.lock ):

for rail only 5

to convert to camel case 5 In the case of snake, put the ultimate key in the initiator:

  # file: config / initializers / json_param_k Ey_transform.rb # JSON- JSON request from conventional camel Transforms the ultimate key # Rail -Complete traditional snake_case: ActionDispatch :: Request.parameter_parsers [: json] = - & gt; (Raw_post) {# action_dispatch / http / parameters.rb Data = ActiveSupport :: Modified data from JSON.decode (raw_post) data = {: _json = & gt; Data) change the camelCase param keys to data.is_a (hash) # Circle: data.deep_transform_keys! (And: underscores)}   

tracks 4.2 (and probably for previous versions)

for Rail 4.2 (and perhaps the earlier version), camel in the case of snakes To convert the absolute keys to the keys, enter it into the initiator: JSON-to-the-Author: JSON-traditional JSON request from #Complete / initializers /json_param_key_transform.rb # Rail-traditional snake_case: Rails.application.config.middleware.swap (:: ActionDispatch :: ParamsParser, :: ActionDispatch :: ParamsParser, :: Mime:: JSON = & gt; Proc.new {| raw_post | # data.deep_transform_keys A Apart from action_dispatch / middleware / borrowed from params_parser.rb (& amp; underscores): #! Data = :: ActiveSupport :: JSON.decode (raw_post) data = {: _json = & gt; data} as long as data.is_a :: hash) data = :: ActionDispatch :: request :: Utils.deep_munge (data) #ComelCase conversion to the ultimate key snake_case:?! Data.deep_transform_keys amp (and;: undersco re)

Restart Rail Server .



No comments:

Post a Comment