diff --git a/json/README.md b/json/README.md new file mode 100644 index 0000000..f2e5f9c --- /dev/null +++ b/json/README.md @@ -0,0 +1 @@ +Source guide: https://jordanorelli.com/post/32665860244/how-to-use-interfaces-in-go diff --git a/json/go.mod b/json/go.mod new file mode 100644 index 0000000..b7ff047 --- /dev/null +++ b/json/go.mod @@ -0,0 +1,3 @@ +module json + +go 1.22.2 diff --git a/json/main.go b/json/main.go new file mode 100644 index 0000000..a112c28 --- /dev/null +++ b/json/main.go @@ -0,0 +1,44 @@ +package main + +import ( + "encoding/json" + "fmt" + "reflect" + "time" +) + +type Timestamp time.Time + +func (t *Timestamp) UnmarshalJSON(b []byte) error { + v, err := time.Parse(time.RubyDate, string(b[1:len(b)-1])) + if err != nil { + return err + } + *t = Timestamp(v) + return nil +} + +// start with a string representation of our JSON data +var input = ` +{ + "created_at": "Thu May 31 00:00:01 +0000 2012" +} +` + +func main() { + // our target will be of type map[string]interface{}, which is a + // pretty generic type that will give us a hashtable whose keys + // are strings, and whose values are of type interface{} + var val map[string]Timestamp + + if err := json.Unmarshal([]byte(input), &val); err != nil { + panic(err) + } + + fmt.Println(val) + for k, v := range val { + fmt.Println(k, reflect.TypeOf(v)) + } + + fmt.Println(time.Time(val["created_at"])) +}