Enjayy
Enjayy

Reputation: 1074

Formatting ruby hash to json

I am current working on formatting some data from ruby into json; My current code looks like this

def line_chart_data
    @sources = ['Facebook','Twitter','Instagram','LinkedIn']
    @sourceCount = [5,12,16,6]
    @weeks = ['one','two','three','four','five','six']

    h = []
    @weeks.each do |i,v|
        h.push({'v' => 'Week ' + i})
        @sourceCount.each do |s|
             h.push({'v' => s})
        end
    end
    c = {c: h}


    #How the data should be formatted on export
    @sources2 = {
      cols: [
        {label: 'Week', type: 'string'},
        #Each Source needs to be looped though and formatted
        {label: 'Facebook', type: 'number'},
        {label: 'Twitter', type: 'number'},
        {label: 'Instagram', type: 'number'},
        {label: 'LinkedIn', type: 'number'}
      ],
      rows: c
     }



    respond_to do |format|
        format.js {render json: @sources2}
    end
end

when the data gets printed to the console it looks like this (shortened it a little for brevity)

"rows":{"c":[{"v":"Week one"},{"v":5},{"v":12},{"v":16},{"v":6},
{"v":"Week two"},{"v":5},{"v":12},{"v":16},{"v":6},
{"v":"Week three"},{"v":5},{"v":12},{"v":16},{"v":6}]}

If you notice the first "c" opens with an array but as it loops through the above code it does not create a new array for each week. The code should look more like this.

"rows":{"c":[{"v":"Week one"},{"v":5},{"v":12},{"v":16},{"v":6}],
{"c":[{"v":"Week two"},{"v":5},{"v":12},{"v":16},{"v":6}]},
{"c":[{"v":"Week three"},{"v":5},{"v":12},{"v":16},{"v":6}]}

Where each loop of weeks array creates a new hash with a key of "c" and a value of array.

any help pointing me in the right direction is greatly appreciated! Been stuck on this for quite a while.

Upvotes: 1

Views: 60

Answers (1)

Martin Konecny
Martin Konecny

Reputation: 59571

You will need to re-work your code a bit to get this. The JSON you want is actually not valid, so this is the closest you can get:

"rows":[{"c":[{"v":"Week one"},{"v":5},{"v":12},{"v":16},{"v":6}],
{"c":[{"v":"Week two"},{"v":5},{"v":12},{"v":16},{"v":6}]},
{"c":[{"v":"Week three"},{"v":5},{"v":12},{"v":16},{"v":6}]}]

Code:

rows = []
@weeks.each do |i,v|
    h = []
    h.push({'v' => 'Week ' + i})
    @sourceCount.each do |s|
         h.push({'v' => s})
    end
    rows.push({"c" => h})
end



#How the data should be formatted on export
@sources2 = {
  cols: [
    {label: 'Week', type: 'string'},
    #Each Source needs to be looped though and formatted
    {label: 'Facebook', type: 'number'},
    {label: 'Twitter', type: 'number'},
    {label: 'Instagram', type: 'number'},
    {label: 'LinkedIn', type: 'number'}
  ],
  rows: rows
 }

Upvotes: 1

Related Questions