加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang的json操作

发布时间:2020-12-16 19:26:56 所属栏目:大数据 来源:网络整理
导读:packagemainimport("encoding/json""fmt""os")typeConfigStructstruct{Hoststring`json:"host"`Portint`json:"port"`AnalyticsFilestring`json:"analytics_file"`StaticFileVersionint`json:"static_file_version"`StaticDirstring`json:"static_dir"`Templa
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)
	}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读