arrays - Formatting ruby hash to json -


i current working on formatting data ruby json; current code looks

def line_chart_data     @sources = ['facebook','twitter','instagram','linkedin']     @sourcecount = [5,12,16,6]     @weeks = ['one','two','three','four','five','six']      h = []     @weeks.each |i,v|         h.push({'v' => 'week ' + i})         @sourcecount.each |s|              h.push({'v' => s})         end     end     c = {c: h}       #how data should formatted on export     @sources2 = {       cols: [         {label: 'week', type: 'string'},         #each source needs looped though , formatted         {label: 'facebook', type: 'number'},         {label: 'twitter', type: 'number'},         {label: 'instagram', type: 'number'},         {label: 'linkedin', type: 'number'}       ],       rows: c      }        respond_to |format|         format.js {render json: @sources2}     end end 

when data gets printed console looks (shortened little 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 notice first "c" opens array loops through above code not create new array each week. code should more 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 new hash key of "c" , value of array.

any pointing me in right direction appreciated! been stuck on quite while.

you need re-work code bit this. json want not valid, closest 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 |i,v|     h = []     h.push({'v' => 'week ' + i})     @sourcecount.each |s|          h.push({'v' => s})     end     rows.push({"c" => h}) end    #how data should formatted on export @sources2 = {   cols: [     {label: 'week', type: 'string'},     #each source needs looped though , formatted     {label: 'facebook', type: 'number'},     {label: 'twitter', type: 'number'},     {label: 'instagram', type: 'number'},     {label: 'linkedin', type: 'number'}   ],   rows: rows  } 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -