Two types of conversion between json byte and map in Golang

Convert between json string and map in Go language

package main
 
import (
    "encoding/json"
    "fmt"
)
 
func main() {
    map2byte2map()
}
 
func map2byte2map() {
 
    map1 := make(map[string]interface{})
    map1["1"] = "hello"
    map1["2"] = "world"
 
    // map to []byte
    str, err := json.Marshal(map1)
 
    if err != nil {
        fmt.Println(err)
    }
 
    // 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"])
 
}

Leave a Reply

Your email address will not be published.

en_USEnglish