在Rails应用程序中解析JAL是camelCase

时间:2013-02-19 12:46:03

标签: ruby-on-rails json camelcasing

我正在编写一个应用程序的后端,而我的前端开发人员强迫我在他正在接收的JSON文件中使用小型camelCase符号(原文如此!)。发送给他这是没有问题的,因为我使用Jbuilder并且可以选择提供这种可能性。但是,我怎样才能以简单的方式解析他的回答?是否有任何选项可以自动使用ActiveSupport String#underscore方法重写所有密钥?

例:
我收到了JSON请求:

{
  'someValue': 324,
  'someOtherValue': 'trolololololo'
}

在Rails中我想用它如下:

@data = JSON.parse(request.body)
@some_value = @data['some_value'] # or @data[:some_value]

1 个答案:

答案 0 :(得分:2)

我找到了一些代码here,所以我再次为您发布,因此很容易复制。

def underscore_key(k)
  if defined? Rails
    k.to_s.underscore.to_sym
  else
    to_snake_case(k.to_s).to_sym
  end
end

def to_snake_case(string)
  string.gsub(/::/, '/').
  gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
  gsub(/([a-z\d])([A-Z])/,'\1_\2').
  tr("-", "_").
  downcase
end

def convert_hash_keys(value)
  case value
    when Array
      value.map { |v| convert_hash_keys(v) }
      # or `value.map(&method(:convert_hash_keys))`
    when Hash
      Hash[value.map { |k, v| [underscore_key(k), convert_hash_keys(v)] }]
    else
      value
  end
end

这里有一些小测试来证明功能:

p convert_hash_keys({abc:"x"})          # => {:abc=>"x"}
p convert_hash_keys({abcDef:"x"})       # => {:abc_def=>"x"}
p convert_hash_keys({AbcDef:"x"})       # => {:abc_def=>"x"}
p convert_hash_keys(["abc"])            # => ["abc"]
p convert_hash_keys([abc:"x"])          # => [{:abc=>"x"}]
p convert_hash_keys([abcDef:"x"])       # => [{:abc_def=>"x"}]

我希望这符合您的要求。