Add json + interfaces exercise
This commit is contained in:
parent
f240e98da4
commit
fb05399eca
|
@ -0,0 +1 @@
|
||||||
|
Source guide: https://jordanorelli.com/post/32665860244/how-to-use-interfaces-in-go
|
|
@ -0,0 +1,3 @@
|
||||||
|
module json
|
||||||
|
|
||||||
|
go 1.22.2
|
|
@ -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"]))
|
||||||
|
}
|
Loading…
Reference in New Issue