Michael Victor
Michael Victor

Reputation: 891

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.

Upvotes: 0

Views: 208

Answers (3)

Enver Dzhaparoff
Enver Dzhaparoff

Reputation: 4421

In action:

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

In .json.jbuilder template:

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

Upvotes: 1

Kristján
Kristján

Reputation: 18803

This is a lovely use case for Array#transpose.

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

Upvotes: 1

nickcen
nickcen

Reputation: 1692

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)

Upvotes: 0

Related Questions