我有一些JSON數據存儲日期時間字符串和總數。例如將JSON作爲基於數據的新對象組合
[{
"Date": "2012-04-01 12:00:00",
"Total": "14"
}, {
"Date": "2012-04-02 06:00:00",
"Total": "3"
}, {
"Date": "2012-04-02 14:00:00",
"Total": "12"
}, {
"Date": "2012-04-02 16:00:00",
"Total": "5"
}, {
"Date": "2012-04-02 17:00:00",
"Total": "7"
}, {
"Date": "2012-04-03 06:00:00",
"Total": "9"
}, {
"Date": "2012-04-03 14:00:00",
"Total": "2"
}, {
"Date": "2012-04-04 06:00:00",
"Total": "1"
}, {
"Date": "2012-04-04 14:00:00",
"Total": "10"
}, {
"Date": "2012-04-04 19:00:00",
"Total": "8"
}, {
"Date": "2012-04-04 21:00:00",
"Total": "4"
}]
我想要做的是創建新的JSON對象的數據是相同的年份,月份和日期。
因此,例如全套的數據可以被格式化爲:
DAY:
[{
"Date": "2012-04-01"
"Total": "3"
},{
"Date": "2012-04-02"
"Total": "4"
},{
"Date": "2012-04-03"
"Total": "6"
}]
月:
[{
"Date": "2012-04"
"Total": "36"
},{
"Date": "2012-05"
"Total": "11"
},{
"Date": "2012-06"
"Total": "23"
},{
"Date": "2012-07"
"Total": "17"
}]
年:
[{
"Date": "2012"
"Total": "91"
},{
"Date": "2013"
"Total": "102"
},{
"Date": "2014"
"Total": "78"
}]
怎麼可能我這樣做是Rails? 如果我能得到一個我如何能做到其中一個的例子,那麼我可以用它作爲其他人的基礎!
所以在控制我有:
def get_count_day
render json: data.to_json
end
def get_count_month
render json: data.to_json
end
def get_count_year
render json: data.to_json
end
我得到一個錯誤'未定義的方法GROUP_BY ' – Cameron
'json'這裏是你在問題 –
中發佈的哈希數組,如果數據是'data.group_by ....' 04-01 12:00:00「, 」Total「:」14「 },{ 」Date「:」2012-04-02 06:00:00「, 」Total「:」3「 } .....]' –