gpt4 book ai didi

json - 无法在 golang 中解析此 json 文件

转载 作者:IT王子 更新时间:2023-10-29 00:38:08 27 4
gpt4 key购买 nike

我正在尝试编写 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 struct 之后。我无法解析问题开头提到的 json 文件。有人可以告诉我如何进行吗?

最佳答案

您可以使用以下结构定义来映射您的 JSON 结构:

type Peer struct{
Pid int
Address string
}

type Config struct{
Peers []Peer
}

Example on play .

关于json - 无法在 golang 中解析此 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21454428/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com