导轨渲染驼峰JSON对象 [英] Rails render json object with camelCase
问题描述
我有一个简单的Rails API以下控制器code:
类API :: V1 :: AccountsController< ApplicationController中
高清指数
渲染JSON:Account.all
结束 高清节目
开始
渲染JSON:Account.includes(:cash_flows).find(PARAMS [:编号]),包括:cash_flows
抢救的ActiveRecord :: RecordNotFound => Ë
头:NOT_FOUND
结束
结束
结束
这里的问题是,所生成的JSON具有格式:
{
ID:2,
名称:简单账户,
现金流: [
{
ID:1,
量:34.3,
介绍:简单描述
},
{
ID:2,
量:1.12,
说明:其他说明
}
]
}
我需要我的生成JSON是驼峰('现金流'而不是'cash_flows')
在此先感谢!
继建议 @TomHert ,我用的JBuilder 和可用的配置:
密钥可以自动使用key_format格式化!这可用于键名从标准ruby_format转换为驼峰
块引用>json.key_format! camelize:低
json.first_name大卫#=> {名字:大卫}
您可以用类方法key_format全局地设置这个(从您的environment.rb比如里面):
块引用>Jbuilder.key_format camelize:低
谢谢!
I have the following controller code in a simple Rails API:
class Api::V1::AccountsController < ApplicationController def index render json: Account.all end def show begin render json: Account.includes(:cash_flows).find(params[:id]), include: :cash_flows rescue ActiveRecord::RecordNotFound => e head :not_found end end end
The problem with this is that, the generated json have the format:
{ id:2, name: 'Simple account', cash_flows: [ { id: 1, amount: 34.3, description: 'simple description' }, { id: 2, amount: 1.12, description: 'other description' } ] }
I need that my generated json is camelCase('cashFlows' instead of 'cash_flows')
Thanks in advance!!!
解决方案Following the recommended by @TomHert, I used JBuilder and the available config:
Keys can be auto formatted using key_format!, this can be used to convert keynames from the standard ruby_format to camelCase:
json.key_format! camelize: :lower json.first_name 'David' # => { "firstName": "David" }
You can set this globally with the class method key_format (from inside your environment.rb for example):
Jbuilder.key_format camelize: :lower
Thanks!!!
这篇关于导轨渲染驼峰JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!