This question already has answers here:
json.Marshal(struct) returns "{}"
(3 answers)
Closed 7 years ago.
I am trying to return a json with a list in each property but I am always obtaining the lists as empty lists. It seems that I have a mistake inside a structure but I cannot found it.
I have two structs:
type CalendarDay struct {
day int `json:"day"`
weekday string `json:"weekday"`
}
type CalendarYear struct {
January []CalendarDay `json:"january"`
February []CalendarDay `json:"february"`
March []CalendarDay `json:"march"`
April []CalendarDay `json:"april"`
May []CalendarDay `json:"may"`
June []CalendarDay `json:"june"`
July []CalendarDay `json:"july"`
August []CalendarDay `json:"august"`
September []CalendarDay `json:"september"`
October []CalendarDay `json:"october"`
November []CalendarDay `json:"november"`
December []CalendarDay `json:"december"`
}
I'm trying to return a json as:
{
"january": [{1 Thursday}, ...]
...
}
but I obatain:
{
"january": [{}, {}, {} ...]
...
}
My API is:
func Calendar(w http.ResponseWriter, r *http.Request) {
fmt.Println("GET /")
year := getYear(2015)
json.NewEncoder(w).Encode(year)
}
func getMonthDays(month time.Month, year int) []CalendarDay {
cdays := []CalendarDay{}
for i := 1; i <= daysIn(month, year); i++ {
date := time.Date(year, month, i, 0, 0, 0, 0, time.UTC)
weekday := date.Weekday()
cday := CalendarDay{
day: date.Day(),
weekday: weekday.String()}
cdays = append(cdays, cday)
}
return cdays
}
func getYear(year int) CalendarYear {
yearCal := CalendarYear{
January: getMonthDays(time.January, year),
February: getMonthDays(time.February, year),
March: getMonthDays(time.March, year),
April: getMonthDays(time.April, year),
May: getMonthDays(time.May, year),
June: getMonthDays(time.June, year),
July: getMonthDays(time.July, year),
August: getMonthDays(time.August, year),
September: getMonthDays(time.September, year),
October: getMonthDays(time.October, year),
November: getMonthDays(time.November, year),
December: getMonthDays(time.December, year)}
return yearCal
}
What am I doing wrong?
Export the fields in CalendarDay by starting the name with an uppercase character.
type CalendarDay struct {
Day int `json:"day"`
Weekday string `json:"weekday"`
}
The encoding/json package and similar packages ignore unexported fields.
Related
I want to merge JSON string in a table and sum its value after group
for Eg:-
2023, {"hen":4, "owl":3}
2023, {"crow":4, "owl":2}
2022, {"owl":6, "crow":2}
2022, {"hen":5}
2021, {"hen":2, "crow":1}
Result could be like below
2023, {"hen":4, "owl":5, "crow":4}
2022, {"hen":5, "owl":6, "crow":2}
2021, {"hen":2, "crow":1}
below might be an option when you don't know json object keys beforehand.
WITH sample_table AS (
SELECT 2023 year, '{"hen":4, "owl":3}' json UNION ALL
SELECT 2023, '{"crow":4, "owl":2}' UNION ALL
SELECT 2022, '{"owl":6, "crow":2}' UNION ALL
SELECT 2022, '{"hen":5}' UNION ALL
SELECT 2021, '{"hen":2, "crow":1}'
)
SELECT year, '{' || STRING_AGG(k || ':' || v, ', ') || '}' json FROM (
SELECT year,
SPLIT(kv, ':')[OFFSET(0)] k,
SUM(SAFE_CAST(SPLIT(kv, ':')[OFFSET(1)] AS INT64)) v
FROM sample_table, UNNEST(SPLIT(TRIM(json, '{}'), ', ')) kv
GROUP BY 1, 2
) GROUP BY 1;
Query results
Consider also below approach
create temp function get_keys(input string) returns array<string> language js as """
return Object.keys(JSON.parse(input));
""";
create temp function get_values(input string) returns array<string> language js as """
return Object.values(JSON.parse(input));
""";
select distinct year,
'{' || string_agg(format('"%s":%i', key ,sum(cast(val as int64))), ', ') over(partition by year) || '}' json
from your_table, unnest(get_keys(json)) key with offset
join unnest(get_values(json)) val with offset
using (offset)
group by year, key
if applied to sample data in your question - output is
So i have a json object which displays year, month and week of year:
{
"year": 2021,
"month": 8,
"week": 31,
},
{
"year": 2021,
"month": 8,
"week": 32,
}
My question is how can i iterate through the json object then convert the week of year into day of month where the day is the end of the week and then pass in the year, month and day of month into a DateTime object in flutter like this:
DateTime(2021,8,7)
DateTime(2021,8,14)
Multiply the week with a 7 to get the total number of days. Like
int totaldays = week*7;
final extraDuration = Duration(days: totaldays);
final startDate = DateTime(2021);
final newDateTime = startDate.add(extraDuration);
print(newDateTime);
print(newDateTime.next(DateTime.friday));
I have a date function with datepicker (with Angular 8), but I have a problem. for example when I enter 36/04/2020, it saves in the database with a date 05/06/2020.
I want when the number of days exceeds the number of days in a month it returns to me the last day (for example in my case it is necessary to enter 30/04/2020).
how to fix this and thank's ?
code .ts:
import { NativeDateAdapter, DateAdapter, MAT_DATE_FORMATS, MatDateFormats } from "#angular/material";
export class AppDateAdapter extends NativeDateAdapter {
parse(value: any): Date | null {
if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
const str = value.split('/');
const year = Number(str[2]);
const month = Number(str[1]) - 1;
const date = Number(str[0]);
return new Date(Date.UTC(year, month, date));
;
}
const timestamp = typeof value === 'number' ? value : Date.parse(value);
return isNaN(timestamp) ? null : new Date(timestamp);
}
createDate(year: number, month: number, date: number): Date {
return new Date(Date.UTC(year, month, date));
}
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
let day: string = date.getUTCDate().toString();
day = +day < 10 ? '0' + day : day;
let month: string = (date.getUTCMonth() + 1).toString();
month = +month < 10 ? '0' + month : month;
let year = date.getUTCFullYear();
return `${day}/${month}/${year}`;
}
// new Date(date.toDateString()).getUTCDate();
return date.toDateString();
}
private _to2digit(n: number) {
return (n);
//return ('00' + n).slice(-2);
}
}
export const APP_DATE_FORMATS =
{
parse: {
dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
},
display: {
// dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
dateInput: 'input',
// monthYearLabel: { month: 'short', year: 'numeric', day: 'numeric' },
monthYearLabel: 'inputMonth',
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'},
}
}
This will give you the last day for month =>
const day = new Date(2020, month + 1, 0)
Then to get date
day.getDate() it will return 31 for January
and finally compare
inputValue = inputValue > day.getDate() ? day.getDate() : inputValue
SELECT * FROM `EVENT` WHERE MONTH(START_DATE) = 7 AND YEAR(START_DATE) = 2019
How to use this query in sequelize with nodejs?
You can use range operators such as $gte, $lte, $gt, $lt:
model.findAll({
where: {
start_date: {
'$gte': new Date("2019-07-01")
}
}
})
How can I convert the following varchar to actual date in MySQL ?
"Thu Nov 07 15:05:22 EST 2013"
I figured that this will solve my problem if I dont care about the time zone:
SELECT STR_TO_DATE( concat( substr( 'Thu Nov 07 15:05:22 est 2013', 1, 20 ) , substr( 'Thu Nov 07 15:05:22 est 2013', 25, 4 ) ) , '%W %b %d %H:%i:%s %Y' );
However if I want I can take out the "est" part and covert that either.