Michael Victor February 2016

Jbuilder - Array to JSON

I have an array named sales which is of the following format --

2015  January   2403
2015  February  2420
2015  March     2320
2015  April     2230

Array Structure - [[2015, "January", 2403], [2015, "February", 2420]]

I'm looking to construct the following json response with jbuilder

{
 months : ['January', 'February', 'March', 'April']
 sales :  [2403, 2420, 2320, 2230]
}

Things I've tried --

I mapped all the months (and similarly sales) into another array with --

@months = @sales.map {|year, month, sales| [month]}

And then in jbuilder --

{"months":[["February"],["January"],["December"],["November"]]}

Which isn't really what I want and neither is it efficient

Some help would be nice.

Answers


nickcen February 2016

require 'json'

datas = [[2015, "January", 2403], [2015, "February", 2420]]

memo = {months: [], sales: []}

datas.reduce(memo) do |memo, data|
  memo[:months] << data[1]
  memo[:sales] << data[2]
  memo
end

puts JSON.generate(memo)


Kristján February 2016

This is a lovely use case for Array#transpose.

years, months, sales = data.transpose
{
  "months": months,
  "sales": sales
}


Enver Dzhaparoff February 2016

In action:

array = [[2015, "January", 2403], [2015, "February", 2420]]
@data = array.transpose

In .json.jbuilder template:

json.months @data[1]
json.sales  @data[2]

Post Status

Asked in February 2016
Viewed 2,418 times
Voted 8
Answered 3 times

Search




Leave an answer