简体   繁体   中英

Rails generating JSON Object

I want to generate a JSON object while fetching data from database.

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:

@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.

And then you define 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.

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

尝试这个。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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