go language json parsing json-iterator
json-iterator is a high performance 100% compatible “encoding/json” replacement
Official website: http://jsoniter.com/
Installation method: go get github.com/json-iterator/go
The usage example is as follows:
package main
import (
"fmt"
jsoniter "github.com/json-iterator/go"
)
type People interface {
getName() string
}
type Student struct {
Name string
Age int
}
func (c *Student) getName() string {
return c.Name
}
func main() {
// struct to json
json := jsoniter.ConfigCompatibleWithStandardLibrary
var p People = &Student{
Name: "John",
Age: 12,
}
structJson, err := json.Marshal(p)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("struct to json", string(structJson))
//map to json
stuMap := make(map[string]interface{})
stuMap["John"] = 12
stuMap["Tom"] = 13
mapJson, err := json.Marshal(stuMap)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("map to json", string(mapJson))
// json to struct
jsonStr := "{\"Name\":\"John\",\"Age\":12}"
var p1 People = new(Student)
err1 := json.Unmarshal([]byte(jsonStr), p1)
if err1 != nil {
fmt.Println(err1)
return
}
fmt.Printf("json to struct: %#v\n", p1)
//json to map
personMap := map[string]interface{}{}
err2 := json.Unmarshal([]byte(jsonStr), &personMap)
if err2 != nil {
fmt.Println(err2)
return
}
fmt.Printf("json to map: %v\n", personMap)
}