英文:
Unable to parse this json file in golang
问题
我正在尝试编写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 Peer struct {
Pid int
Address string
}
type Config struct {
Peers []Peer
}
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文件。请问有人可以告诉我如何继续吗?
英文:
I am trying to write go code to parse the following of json file:
{
"peers": [
{
"pid": 1,
"address": "127.0.0.1:17001"
},
{
"pid": 2,
"address": "127.0.0.1:17002"
}
]
}
What I could do so far is write this code:
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)
}
Above code works for non-nested json files like following one:
{
"pid": 1,
"address": "127.0.0.1:17001"
}
But even after changing the Config struct
so many times. I am not able to parse the json file mentioned at the start of the question. Can somebody please tell me how to proceed?
答案1
得分: 8
你可以使用以下结构定义来映射你的JSON结构:
type Peer struct{
Pid int
Address string
}
type Config struct{
Peers []Peer
}
英文:
You can use the following struct definition to map your JSON structure:
type Peer struct{
Pid int
Address string
}
type Config struct{
Peers []Peer
}
答案2
得分: 0
要包含自定义属性名称,请添加结构字段标签,如下所示:
type Peer struct {
CustomId int `json:"pid"`
CustomAddress string `json:"address"`
}
这样,当将Peer
结构体转换为JSON时,属性名称将被自定义为pid
和address
。
英文:
To include custom attribute names, add struct field tags as:
type Peer struct{
CustomId int `json:"pid"`
CustomAddress string `json:"address"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论