A method for converting Go structures arrays dictionaries and json strings to and from one another
- 2020-07-21 08:25:13
- OfStack
In Go, the encoding/json package can easily convert structures, arrays, and dictionaries to json strings.
reference
import "encoding/json"
Parsing grammar
// v Pass in instance variables such as structure, array, etc
// []byte An array of bytes
// error There may be mistakes
func Marshal(v interface{}) ([]byte, error)
The parsing
// []byte An array of bytes
// v Pass in the pointer address of an instance variable such as a structure, array, etc
// error There may be mistakes
func Unmarshal(data []byte, v interface{}) error
code
package main
// https://golang.org/pkg/encoding/json/
// https://cloud.tencent.com/developer/section/1141542#stage-100023262
import (
"fmt"
"encoding/json"
)
type User struct {
Id int `json:"id"`
Name string `json:"name"`
}
func main() {
// A string is resolved into a structure
s := `{"id": 1, "name": "wxnacy"}`
var user User
// Unparses a string into a structure
json.Unmarshal([]byte(s), &user)
fmt.Println(user) // {1 wxnacy}
var d map[string]interface{}
// Unparse a string into a dictionary
json.Unmarshal([]byte(s), &d)
fmt.Println(d) // map[id:1 name:wxnacy]
s = `[1, 2, 3, 4]`
var a []int
// Unparses strings into arrays
json.Unmarshal([]byte(s), &a)
fmt.Println(a) // [1 2 3 4]
// Parse the structure into a string
b, e := json.Marshal(user)
fmt.Println(e)
fmt.Println(string(b)) // {"id":1,"name":"wxnacy"}
b, e = json.Marshal(a)
fmt.Println(string(b), e) // [1,2,3,4] <nil>
b, e = json.Marshal(d)
fmt.Println(string(b), e) // {"id":1,"name":"wxnacy"} <nil>
}