package jsons import ( "strconv" "encoding/json" //"errors" "time" ) // The package implements basic types // to be used in structures that can be parsed // from the poorly structured JSON. (Like ones that make IDs strings) func parseInt(str string, n int) (int64, error) { if str == "" { return 0, EmptyStringErr } if str[0] == '"' { str = str[1:] } if str == "" { return 0, EmptyStringErr } if str[len(str)-1] == '"' { str = str[:len(str)-1] } v, err := strconv.ParseInt(str, 10, n) if err != nil { return 0, err } return v, nil } type Int int func(ji *Int) UnmarshalJSON(bts []byte) error { v, err := parseInt(string(bts), 32) if err != nil { return err } *ji = Int(v) return nil } type Int64 int64 func(ji *Int64) UnmarshalJSON(bts []byte) error { v, err := parseInt(string(bts), 64) if err != nil { return err } *ji = Int64(v) return nil } type ArrayMap[V any] map[int] V func (jam *ArrayMap[V]) UnmarshalJSON(bts []byte) error { *jam = make(ArrayMap[V]) am := *jam j := map[string] json.RawMessage{} err := json.Unmarshal(bts, &j) if err != nil { return err } v := new(V) for jk, jv := range j { // Getting the key from string. k, err := strconv.ParseInt(jk, 10, 32) if err != nil { return err } err = json.Unmarshal([]byte(jv), v) if err != nil { return err } am[int(k)] = *v } return nil } type Timestamp int64 func (ts *Timestamp) UnmarshalJSON(bts []byte) error { i, err := parseInt(string(bts), 64) if err != nil { return err } *ts = Timestamp(i) return nil } func (ts Timestamp) Time() time.Time { return time.Unix(int64(ts), 0) }