Add json + interfaces exercise

This commit is contained in:
raul 2024-04-16 08:54:21 +02:00
parent f240e98da4
commit fb05399eca
3 changed files with 48 additions and 0 deletions

1
json/README.md Normal file
View File

@ -0,0 +1 @@
Source guide: https://jordanorelli.com/post/32665860244/how-to-use-interfaces-in-go

3
json/go.mod Normal file
View File

@ -0,0 +1,3 @@
module json
go 1.22.2

44
json/main.go Normal file
View File

@ -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"]))
}