go语言中的json与map相互转换

 主要是引入 "encoding/json" 包;用到的也就是其中的两个函数json.Marshal和json.Unmarshal。

1、json.Marshal

#函数定义位于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

#函数定义位于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类型才可以。

 

// 当前程序的包名
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"])
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

焱齿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值