go - How to parse non standard time format from json in golang? -


lets have following json

{     name: "john",     birth_date: "1996-10-07" } 

and want decode following structure

type person struct {     name string `json:"name"`     birthdate time.time `json:"birth_date"` } 

like this

person := person{}  decoder := json.newdecoder(req.body);  if err := decoder.decode(&person); err != nil {     log.println(err) } 

which gives me error parsing time ""1996-10-07"" ""2006-01-02t15:04:05z07:00"": cannot parse """ "t"

if parse manually this

t, err := time.parse("2006-01-02", "1996-10-07") 

but when time value json string how decoder parse in above format?

that's case when need implement custom marshal und unmarshal functions.

unmarshaljson(b []byte) error { ... }  marshaljson() ([]byte, error) { ... } 

by following example in golang documentation of json package like:

// first create type alias type jsonbirthdate time.time  // add struct type person struct {     name string `json:"name"`     birthdate jsonbirthdate `json:"birth_date"` }  // imeplement marshaler und unmarshalere interface func (j *jsonbirthdate) unmarshaljson(b []byte) error {     s := strings.trim(string(b), "\"")     t, err := time.parse("2006-01-02", s)     if err != nil {         return err     }     *j = jb(t)     return nil }  func (j jsonbirthdate) marshaljson() ([]byte, error) {     return json.marshal(j) }  // maybe format function printing date func (j jsonbirthdate) format(s string) string {     t := time.time(j)     return t.format(s) } 

Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -