【问题标题】:Rails render json object with camelCaseRails 使用 camelCase 渲染 json 对象
【发布时间】:2014-07-10 18:00:15
【问题描述】:

我在一个简单的 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

问题在于,生成的 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')

提前致谢!!!

【问题讨论】:

标签: ruby-on-rails ruby json api


【解决方案1】:

按照@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

谢谢!!!

【讨论】:

    猜你喜欢
    • 2017-04-20
    • 2015-11-28
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    相关资源
    最近更新 更多