无法在golang中解析此json文件
发布时间:2020-12-16 09:27:16 所属栏目:大数据 来源:网络整理
导读:我正在尝试编写go代码来解析json文件的以下内容: { "peers": [ { "pid": 1,"address": "127.0.0.1:17001" },{ "pid": 2,"address": "127.0.0.1:17002" } ]} 到目前为止我能做的就是编写这段代码: package mainimport ( "fmt" "io/ioutil" "encoding/json")
我正在尝试编写go代码来解析json文件的以下内容:
{ "peers": [ { "pid": 1,"address": "127.0.0.1:17001" },{ "pid": 2,"address": "127.0.0.1:17002" } ] } 到目前为止我能做的就是编写这段代码: package main import ( "fmt" "io/ioutil" "encoding/json" ) type Config struct{ Pid int Address string } func main(){ content,err := ioutil.ReadFile("config.json") if err!=nil{ fmt.Print("Error:",err) } var conf Config err=json.Unmarshal(content,&conf) if err!=nil{ fmt.Print("Error:",err) } fmt.Println(conf) } 上面的代码适用于非嵌套的json文件,如下所示: { "pid": 1,"address": "127.0.0.1:17001" } 但即使在更改Config结构这么多次之后.我无法解析问题开头提到的json文件.有人可以告诉我怎么办? 解决方法
您可以使用以下结构定义来映射JSON结构:
type Peer struct{ Pid int Address string } type Config struct{ Peers []Peer } Example on play. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |