CodeFun Go

JSON与切片数组相互解析

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

数组/切片转json

jsonBytes, error := json.Marshal(slice)

json转数组/切片

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

import (
    "fmt"
    "encoding/json"
)

func main() {
    // slice/array to json
    s := []string{"apple", "peach", "pear"}
    slcB, _ := json.Marshal(s)
    fmt.Println(string(slcB))

    // json to slice/array
    s1 := make([]string, 0)
    if err := json.Unmarshal(slcB, &s1); err != nil {
        panic(err)
    }
    fmt.Printf("type: %T, content: %v\n", s1, s1)
}
["apple","peach","pear"]
type: []string, content: [apple peach pear]