How to convert utf8 string to []byte?

后端 未结 2 895
深忆病人
深忆病人 2021-01-28 17:10

I want to unmarshal a string that contains JSON, however the Unmarshal function takes a []byte as input.

How can I convert my UTF8

2条回答
  •  旧巷少年郎
    2021-01-28 17:29

    just use []byte(s) on the string. for example:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func main() {
        s := `{"test":"ok"}`
        var data map[string]interface{}
        if err := json.Unmarshal([]byte(s), &data); err != nil {
            panic(err)
        }
        fmt.Printf("json data: %v", data)
    }
    

    check it out on the playground here.

提交回复
热议问题