导轨渲染驼峰JSON对象 [英] Rails render json object with camelCase

查看:138
本文介绍了导轨渲染驼峰JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆