golang parses map[string]interface{} and json to struct

When developing and parsing json data, I first wrote the following test code to judge the format of the data. I have to say that strongly typed languages have this kind of inconvenience.

At the same time, pay attention to the following items:

 The parsed int type will become float64 type
 Pay attention to the interaction with the front-end. In some cases, the front-end will have precision problems when parsing int64. If it involves front-end interaction, try to avoid using int64, or convert it into a string before interacting with the front-end.
func GuessType(k string, v interface{})  {
  switch value := v.(type) {
  case nil:
    fmt.Println(k, "is nil", "null")
  case string:
    fmt.Println(k, "is string", value)
  case int:
    fmt.Println(k, "is int", value)
  case float64:
    fmt.Println(k, "is float64", value)
  case []interface{}:
    fmt.Println(k, "is an array:")
    for i, u := range value {
      fmt.Println(i, u)
    }
  case map[string]interface{}:
    fmt.Println(k, "is an map:")
  default:
    fmt.Println(k, "is unknown type", fmt.Sprintf("%T", v))
  }
}
func GuessTypeFromMapStringInterface(m map[string]interface{}){
  for k, v := range m {
    GuessType(k,v)
  }
}

Convert map[string]interface{} and json into struct

Going down from the previous step, use the formatting commands in the encoding/json library to format the json first, and then unformat it into a struct:

import "encoding/json"
  tmpJson, err := json.Marshal(data)
  if err != nil {
    return nil, err
  }
  create := KeluTest{}
  json.Unmarshal(tmpJson, &create)

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish