Rails 使用camelCase 渲染json 对象 [英] Rails render json object with camelCase
问题描述
我在一个简单的 Rails API 中有以下控制器代码:
class Api::V1::AccountsController <应用控制器定义索引渲染 json:Account.all结尾高清秀开始渲染 json: Account.includes(:cash_flows).find(params[:id]), include: :cash_flows救援 ActiveRecord::RecordNotFound =>电子头 :not_found结尾结尾结尾
问题在于,生成的 json 格式如下:
<代码>{编号:2,name: '简单账户',现金流: [{编号:1,金额:34.3,description: '简单描述'},{编号:2,金额:1.12,描述:'其他描述'}]}
我需要我生成的json是camelCase('cashFlows'而不是'cash_flows')
提前致谢!!!
按照 @TomHert 的推荐,我使用了 JBuilder 和可用的配置:
<块引用>可以使用 key_format! 自动格式化键,这可用于将键名从标准 ruby_format 转换为驼峰式:
json.key_format!骆驼::降低json.first_name '大卫'# =>{名字":大卫"}
<块引用>
您可以使用类方法 key_format 全局设置它(例如从您的 environment.rb 中):
Jbuilder.key_format camelize::lower
谢谢!!!
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!!!
这篇关于Rails 使用camelCase 渲染json 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!