ArnovLiere

Untitled

Jan 26th, 2021
623
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "encoding/json"
  6.     ms "github.com/mitchellh/mapstructure"
  7. )
  8.  
  9. type Value struct {
  10.     Key      string
  11.     OtherKey interface{}
  12. }
  13.  
  14. type OtherKeyValue struct {
  15.     OtherOtherKey string
  16. }
  17.  
  18. func main() {
  19.     // Construct value to marshal
  20.     val := Value{Key: "yo", OtherKey: OtherKeyValue{OtherOtherKey: "yo2"}}
  21.     fmt.Printf("Struct: %v\n", val)
  22.  
  23.     // Marshal
  24.     b, err := json.Marshal(val)
  25.     if err != nil {
  26.         fmt.Printf("Error marshalling: %s\n", err)
  27.         return
  28.     }
  29.     fmt.Printf("Marshalled: %s\n", string(b))
  30.  
  31.     // Unmarshal
  32.     var toFill Value
  33.     if err := json.Unmarshal(b, &toFill); err != nil {
  34.         fmt.Printf("Error unmarshalling: %s\n", err)
  35.         return
  36.     }
  37.     fmt.Printf("Unmarshalled: %v\n", toFill)
  38.  
  39.     // Cast
  40.     var otherKeyValue OtherKeyValue
  41.     ms.Decode(toFill.OtherKey, &otherKeyValue)
  42.     fmt.Printf("Other key value: %v\n", otherKeyValue)
  43. }
  44.  
RAW Paste Data