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热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬