-1

I have a rails4 app, where one of the controllers have a variable @data in my controller as follows:

@data = {
  2013 => {sal: 1000, exp: 400},
  2014 => {sal: 1170, exp: 460},
  2015 => {sal: 660, exp: 1120},
  2016 => {sal: 1030, exp: 540}
}

I have associated json jbuilder file where I want to use this to render json in this structure

[
  ['Year', 'Sales', 'Expenses'],
  ['2013',  1000,      400],
  ['2014',  1170,      460],
  ['2015',  660,       1120],
  ['2016',  1030,      540]
]

I was looking at https://github.com/rails/jbuilder, but could not figure out as how to achieve my goal.

This did not help..

json.array! @data do |d|
  ???
end

Any help will be appreciated!

JVK
  • 3,782
  • 8
  • 43
  • 67
  • I don't think it's a good way to render json arrays. Hashes is a much cleaner and meaningful way, I would render `@data` rather than the array-style. – Tamer Shlash May 27 '14 at 22:04
  • Not sure about downvoter, as what is the reason behind downvoting? – JVK May 29 '14 at 18:41

1 Answers1

0

I guess jbuilder don't fit for your purpose. You want arrays, and it returns hashes.

It could be done with:

@data = {
  2013 => {sal: 1000, exp: 400},
  2014 => {sal: 1170, exp: 460},
  2015 => {sal: 660, exp: 1120},
  2016 => {sal: 1030, exp: 540}
}
@mod_data = [['Year', 'Sales', 'Expenses']]
@data.each { |k, v| @mod_data << [k, v[:sal], v[:exp]] }

# or briefly, but perhaps less readable

@data.each_with_object([['Year', 'Sales', 'Expenses']]) { |(k, v), o| o << [k, v[:sal], v[:exp]] } # returns array
zishe
  • 10,665
  • 12
  • 64
  • 103
  • 1
    I can very well convert my hash to array. But that is not what I am looking for. I want let jbuilder do this json building. So you are saying there is no way to do it in jbuilder? – JVK May 27 '14 at 21:26
  • I'm not sure 100 percent, perhaps someone will provide another answer. – zishe May 27 '14 at 21:28