主要是引入 "encoding/json" 包;用到的也就是其中的两个函数json.Marshal和json.Unmarshal。
1、json.Marshal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#函数定义位于GOROOT or GOPATH的/src/encoding/json/encode.go 中
func Marshal(v interface{}) ([]byte, error) { e := newEncodeState()
err := e.marshal(v, encOpts{escapeHTML: true}) if err != nil { return nil, err } buf := append([]byte(nil), e.Bytes()...)
encodeStatePool.Put(e)
return buf, nil } |
2、json.Unmarshal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#函数定义位于GOROOT or GOPATH的/src/encoding/json/decode.go 中
func Unmarshal(data []byte, v interface{}) error { // Check for well-formedness. // Avoids filling out half a data structure // before discovering a JSON syntax error. var d decodeState err := checkValid(data, &d.scan) if err != nil { return err }
d.init(data) return d.unmarshal(v) }
#输入的数据类型是[]byte,string类型的话要转成[]byte. str1 := "hello" data := []byte(str1) // 将字符串转为[]byte类型 |
可见其输入数据的类型是[]byte。对于string类型的数据要转成[]byte类型才可以。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// 当前程序的包名 package main
// 导入其它的包 import ( "encoding/json" "fmt" )
func main() { map2json2map() }
func map2json2map() {
map1 := make(map[string]interface{}) map1["1"] = "hello" map1["2"] = "world" //return []byte str, err := json.Marshal(map1)
if err != nil { fmt.Println(err) } fmt.Println("map to json", string(str))
//json([]byte) to map map2 := make(map[string]interface{}) err = json.Unmarshal(str, &map2) if err != nil { fmt.Println(err) } fmt.Println("json to map ", map2) fmt.Println("The value of key1 is", map2["1"]) } |