Cameron Cameron - 2 months ago 7
JSON Question

Group JSON as new objects based on data

I have some JSON data that stores a date time string and total. e.g.

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


What I'd like to do is create new JSON objects for data that is the same year, month, and day.

So for example a full set of data could be formatted into:

DAY:

[{
"Date": "2012-04-01"
"Total": "3"
},{
"Date": "2012-04-02"
"Total": "4"
},{
"Date": "2012-04-03"
"Total": "6"
}]


MONTH:

[{
"Date": "2012-04"
"Total": "36"
},{
"Date": "2012-05"
"Total": "11"
},{
"Date": "2012-06"
"Total": "23"
},{
"Date": "2012-07"
"Total": "17"
}]


YEAR:

[{
"Date": "2012"
"Total": "91"
},{
"Date": "2013"
"Total": "102"
},{
"Date": "2014"
"Total": "78"
}]


How could I do this is Rails? If I could get an example of how I could do one of them, then I could then use that as a base to do the others!

So in the controller I have:

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

Answer

Hey you can try this way for Day

given_json.group_by{|b| b["Date"].to_date.strftime("%Y-%d-%m")}.collect{|key,value| {"Date" =>key , "Total" => value.sum{|d| d["Total"].to_i}}}

For Month

given_json.group_by{|b| b["Date"].to_date.strftime("%Y-%m")}.collect{|key,value| {"Date" =>key , "Total" => value.sum{|d| d["Total"].to_i}}}

For Year

given_json.group_by{|b| b["Date"].to_date.strftime("%Y")}.collect{|key,value| {"Date" =>key , "Total" => value.sum{|d| d["Total"].to_i}}}
Comments