2015-05-14 79 views
1

我目前正在從紅寶石格式化一些數據到json; 我當前的代碼看起來像這樣格式化紅寶石散列json

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 

當數據被打印到控制檯,它看起來像這樣(縮短了一點爲簡潔起見)

"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}]} 

如果您發現的第一個「C」打開有一個數組,但是當它循環遍歷上面的代碼時,它不會爲每週創建一個新的數組。代碼應該看起來更像這樣。

"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}]} 

週數組的每個循環創建一個新的散列,其中鍵爲「c」和數組的值。

任何幫助指出我在正確的方向非常感謝!已經停留了很長一段時間。

回答

1

您需要重新處理您的代碼以獲取此代碼。你想要的JSON實際上是無效的,所以這是最接近你可以得到:

"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}]}] 

代碼:

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 
} 
+0

謝謝@馬丁真的救了我大量的時間!我知道我每次嘗試在'@weeks'裏面初始化h時都會出錯,它會發生錯誤。 – Enjayy