Rails使用camelCase呈现json对象
我在一个简单的Rails API中有以下控制器代码:
class Api::V1::AccountsController e head :not_found end end end
这个问题是,生成的json具有以下格式:
{ id:2, name: 'Simple account', cash_flows: [ { id: 1, amount: 34.3, description: 'simple description' }, { id: 2, amount: 1.12, description: 'other description' } ] }
我需要我生成的json是camelCase (’cashFlows’而不是’cash_flows’)
提前致谢!!!
按照@TomHert的推荐,我使用了JBuilder和可用的配置:
可以使用key_format!自动格式化密钥,这可以用于将标准ruby_format中的键名转换为camelCase:
json.key_format! camelize: :lower json.first_name 'David' # => { "firstName": "David" }
您可以使用类方法key_format(例如,在environment.rb中)全局设置它:
Jbuilder.key_format camelize: :lower
谢谢!!!