CodeFun Go

JSON与映射(map)相互解析

encoding/json包提供了Marshal与Unmarshal函数,可用于将 golang 数组、切片、映射、结构体转换为 JSON 字符串,反之亦然。

map转json

jsonBytes, error := json.Marshal(map)

json转map

err := json.Unmarshal(jsonBytes, &map);
package main

import (
    "fmt"
    "encoding/json"
)

func main() {
    //map to json
    m := map[string]int{"apple": 5, "lettuce": 7}
    mapB, _ := json.Marshal(m)
    fmt.Println(string(mapB))

    // json to map
    m1 := make(map[string]int, 0)
    if err := json.Unmarshal(mapB, &m1); err != nil {
        panic(err)
    }
    fmt.Printf("type: %T, content: %v\n", m1, m1)
}
{"apple":5,"lettuce":7}
type: map[string]int, content: map[apple:5 lettuce:7]