简体   繁体   English

Rails生成JSON对象

[英]Rails generating JSON Object

I want to generate a JSON object while fetching data from database. 我想在从数据库中获取数据时生成一个JSON对象。

def duration
  return @data[:duration] unless @data[:duration].nil?

  @data[:duration] = per_hour.collect do | val |
    [val[0], val[1]]
  end
end

I get the data I need, but the array isn't correct. 我得到了我需要的数据,但是数组不正确。 My view looks like: 我的看法如下:

var array = <%= raw @duration_data.to_json %>;

And my array looks like this: 我的数组如下所示:

var array = [{"data": [[0,0],[1,60.0]] }];

But what I need is this: 但是我需要的是:

var array = [{"data": {"0":0, "1":60.0} }];

You just need to convert your array to a hash: 您只需要将数组转换为哈希即可:

@data[:duration] = per_hour.collect do |val|
  [val[0], val[1]]
end.to_h

For Ruby 1.9: 对于Ruby 1.9:

@data[:duration] = Hash[*per_hour.collect { |val| [val[0], val[1]] }]

I would write this as follows: 我会这样写:

def duration
  @data[:duration] ||= build_duration
end 

This is a short way to say: return @data[:duration] if not nil, otherwise, assign build_duration to it. 这是一种简短的说法:如果不是nil,则返回@data[:duration] ,否则,将build_duration分配给它。

And then you define build_duration 然后定义build_duration

def build_duration
  result = {}
  per_hour.each do |val|
    result[val[0]] = val[1]
  end
  result
end

You can write the build_duration more compact, but for me this is very readable: it will build a hash and fill it up as you wish. 您可以编写更紧凑的build_duration ,但是对我来说,这是很build_duration :它将构建一个哈希并根据需要填充它。

@data[:duration] ||= per_hour.collect { | val | [val[0], val[1]] }.to_h

尝试这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM