golang的json操作
本文内容纲要:
packagemain
import(
"encoding/json"
"fmt"
"os"
)
typeConfigStructstruct{
Hoststring`json:"host"`
Portint`json:"port"`
AnalyticsFilestring`json:"analytics_file"`
StaticFileVersionint`json:"static_file_version"`
StaticDirstring`json:"static_dir"`
TemplatesDirstring`json:"templates_dir"`
SerTcpSocketHoststring`json:"serTcpSocketHost"`
SerTcpSocketPortint`json:"serTcpSocketPort"`
Fruits[]string`json:"fruits"`
}
typeOtherstruct{
SerTcpSocketHoststring`json:"serTcpSocketHost"`
SerTcpSocketPortint`json:"serTcpSocketPort"`
Fruits[]string`json:"fruits"`
}
funcmain(){
jsonStr:=`{"host":"http://localhost:9090","port":9090,"analytics_file":"","static_file_version":1,"static_dir":"E:/Project/goTest/src/","templates_dir":"E:/Project/goTest/src/templates/","serTcpSocketHost":":12340","serTcpSocketPort":12340,"fruits":["apple","peach"]}`
//jsonstr转map
vardatmap[string]interface{}
iferr:=json.Unmarshal([]byte(jsonStr),&dat);err==nil{
fmt.Println("==============jsonstr转map=======================")
fmt.Println(dat)
fmt.Println(dat["host"])
}
//jsonstr转struct
varconfigConfigStruct
iferr:=json.Unmarshal([]byte(jsonStr),&config);err==nil{
fmt.Println("================jsonstr转struct==")
fmt.Println(config)
fmt.Println(config.Host)
}
//jsonstr转struct(部份字段)
varpartOther
iferr:=json.Unmarshal([]byte(jsonStr),&part);err==nil{
fmt.Println("================jsonstr转struct==")
fmt.Println(part)
fmt.Println(part.SerTcpSocketPort)
}
//struct到jsonstr
ifb,err:=json.Marshal(config);err==nil{
fmt.Println("================struct到jsonstr==")
fmt.Println(string(b))
}
//map到jsonstr
fmt.Println("================map到jsonstr=====================")
enc:=json.NewEncoder(os.Stdout)
enc.Encode(dat)
//array到jsonstr
arr:=[]string{"hello","apple","python","golang","base","peach","pear"}
lang,err:=json.Marshal(arr)
iferr==nil{
fmt.Println("================array到jsonstr==")
fmt.Println(string(lang))
}
//json到[]string
varwo[]string
iferr:=json.Unmarshal(lang,&wo);err==nil{
fmt.Println("================json到[]string==")
fmt.Println(wo)
}
}
本文内容总结:
原文链接:https://www.cnblogs.com/go-ios/p/3906251.html