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

huangapple go评论107阅读模式
英文:

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
}

在playground上的示例

英文:

You can use the following struct definition to map your JSON structure:

type Peer struct{
	Pid int
	Address string
}

type Config struct{
	Peers []Peer
}

Example on play.

答案2

得分: 0

要包含自定义属性名称,请添加结构字段标签,如下所示:

type Peer struct {
    CustomId        int    `json:"pid"`
    CustomAddress   string `json:"address"`
}

这样,当将Peer结构体转换为JSON时,属性名称将被自定义为pidaddress

英文:

To include custom attribute names, add struct field tags as:

type Peer struct{
        CustomId int `json:"pid"` 
        CustomAddress string `json:"address"`
    }

huangapple
  • 本文由 发表于 2014年1月30日 18:54:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/21454428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定