1. 程式人生 > 其它 >Go語言map與json串相互轉化

Go語言map與json串相互轉化

1、Go語言map與json串相互轉化

  • map轉為Json串(本質是string),先把map轉為byte陣列,再把byte陣列轉為Json串
  • Json串(本質是string)轉為map,先把Json串轉為byte陣列,再把byte陣列轉為map
package main

import (
   "encoding/json"
   "fmt"
)

func main() {
   //map轉為json串(本質是string)
   //先把map轉為byte陣列
   //再把byte陣列轉為json串
   DataMap := map[string]int{"a": 1, "b": 2, "c": 3}
   marshal, err := json.Marshal(DataMap)
   if err != nil {
      fmt.Printf("Map轉化為byte陣列失敗,異常:%s\n", err)
      return
   }
   fmt.Printf("Map轉化為byte陣列成功:%v\n", marshal)
   fmt.Printf("byte陣列轉化為Json串成功:%s\n", string(marshal))

   //json串(本質是string)轉為map
   //先把json串轉為byte陣列
   //再把byte陣列轉為map
   dataStr := `{"a":1,"b":2,"c":3}`
   var dataMap map[string]int
   err = json.Unmarshal([]byte(dataStr), &dataMap)
   if err != nil {
      fmt.Printf("Json串轉化為Map失敗,異常:%s\n", err)
      return
   }
   fmt.Printf("Json串(本質是string)轉化為Map成功:%v", dataMap)
}