go語言中json轉成map結構,新增根的元素
阿新 • • 發佈:2019-01-27
package main
import (
"encoding/json"
"fmt"
"log"
)
type A struct {
Name string `json:"name"`
Age string `json:"name"`
}
type B struct {
Bname string `json:"bName"`
}
type C struct {
Cname string `json:"cName"`
}
type D struct {
DataA A `json:"dataA"`
DataB B `json:"dataB"`
DataC C `json:"dataC"`
}
func main() {
var d D
d.DataA.Age = "DataA.Age"
d.DataA.Name = "DataA.Name"
d.DataB.Bname = "DataB.Bname"
d.DataC.Cname = "DataC.Cname"
buffer, err := json.Marshal(d)
if err != nil {
log.Println(err)
}
var jsonStruct map[string ]interface{}
if err := json.Unmarshal(buffer, &jsonStruct); err != nil {
log.Println(err)
}
jsonStruct["token"] = "--------------------------"
buffer, err = json.Marshal(jsonStruct)
if err != nil {
log.Println(err)
}
fmt.Println(string(buffer[:]))
}
//----------------------------------
{"dataA":{},"dataB":{"bName":"DataB.Bname"},"dataC":{"cName":"DataC.Cname"},"token":"--------------------------"}