打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
golang的json操作
package mainimport (	"encoding/json"	"fmt"	"os")type ConfigStruct struct {	Host              string   `json:"host"`	Port              int      `json:"port"`	AnalyticsFile     string   `json:"analytics_file"`	StaticFileVersion int      `json:"static_file_version"`	StaticDir         string   `json:"static_dir"`	TemplatesDir      string   `json:"templates_dir"`	SerTcpSocketHost  string   `json:"serTcpSocketHost"`	SerTcpSocketPort  int      `json:"serTcpSocketPort"`	Fruits            []string `json:"fruits"`}type Other struct {	SerTcpSocketHost string   `json:"serTcpSocketHost"`	SerTcpSocketPort int      `json:"serTcpSocketPort"`	Fruits           []string `json:"fruits"`}func main({		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"]}`	//json str 转map	var dat map[string]interface{}	if err := json.Unmarshal([]byte(jsonStr), &dat); err == nil {		fmt.Println("==============json str 转map=======================")		fmt.Println(dat)		fmt.Println(dat["host"])	}	//json str 转struct	var config ConfigStruct	if err := json.Unmarshal([]byte(jsonStr), &config); err == nil {		fmt.Println("================json str 转struct==")		fmt.Println(config)		fmt.Println(config.Host)	}	//json str 转struct(部份字段)	var part Other	if err := json.Unmarshal([]byte(jsonStr), &part); err == nil {		fmt.Println("================json str 转struct==")		fmt.Println(part)		fmt.Println(part.SerTcpSocketPort)	}	//struct 到json str	if b, err := json.Marshal(config); err == nil {		fmt.Println("================struct 到json str==")		fmt.Println(string(b))	}	//map 到json str	fmt.Println("================map 到json str=====================")	enc := json.NewEncoder(os.Stdout)	enc.Encode(dat)	//array 到 json str	arr := []string{"hello""apple""python""golang""base""peach""pear"}	lang, err := json.Marshal(arr)	if err == nil {		fmt.Println("================array 到 json str==")		fmt.Println(string(lang))	}	//json 到 []string	var wo []string	if err := json.Unmarshal(lang, &wo); err == nil {		fmt.Println("================json 到 []string==")		fmt.Println(wo)	}}

转自:https://my.oschina.net/golang/blog/210012

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
golang之json小谈
使用Golang开发微信公众平台
Golang 语言中怎么解码 4 种常见JSON 格式数据?
深入探讨 Golang 中的追加操作
Golang 新手可能会踩的 50 个坑
诚之和:如何使用Go语言JSON 标准库
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服