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

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

Unable to parse this json file in golang

问题

我正在尝试编写Go代码来解析以下JSON文件的内容:

  1. {
  2. "peers": [
  3. {
  4. "pid": 1,
  5. "address": "127.0.0.1:17001"
  6. },
  7. {
  8. "pid": 2,
  9. "address": "127.0.0.1:17002"
  10. }
  11. ]
  12. }

到目前为止,我写了以下代码:

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "encoding/json"
  6. )
  7. type Peer struct {
  8. Pid int
  9. Address string
  10. }
  11. type Config struct {
  12. Peers []Peer
  13. }
  14. func main() {
  15. content, err := ioutil.ReadFile("config.json")
  16. if err != nil {
  17. fmt.Print("Error:", err)
  18. }
  19. var conf Config
  20. err = json.Unmarshal(content, &conf)
  21. if err != nil {
  22. fmt.Print("Error:", err)
  23. }
  24. fmt.Println(conf)
  25. }

上述代码可以解析非嵌套的JSON文件,例如以下文件:

  1. {
  2. "pid": 1,
  3. "address": "127.0.0.1:17001"
  4. }

但是,即使我多次更改了Config结构体,我仍然无法解析问题开头提到的JSON文件。请问有人可以告诉我如何继续吗?

英文:

I am trying to write go code to parse the following of json file:

  1. {
  2. "peers": [
  3. {
  4. "pid": 1,
  5. "address": "127.0.0.1:17001"
  6. },
  7. {
  8. "pid": 2,
  9. "address": "127.0.0.1:17002"
  10. }
  11. ]
  12. }

What I could do so far is write this code:

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "encoding/json"
  6. )
  7. type Config struct{
  8. Pid int
  9. Address string
  10. }
  11. func main(){
  12. content, err := ioutil.ReadFile("config.json")
  13. if err!=nil{
  14. fmt.Print("Error:",err)
  15. }
  16. var conf Config
  17. err=json.Unmarshal(content, &conf)
  18. if err!=nil{
  19. fmt.Print("Error:",err)
  20. }
  21. fmt.Println(conf)
  22. }

Above code works for non-nested json files like following one:

  1. {
  2. "pid": 1,
  3. "address": "127.0.0.1:17001"
  4. }

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结构:

  1. type Peer struct{
  2. Pid int
  3. Address string
  4. }
  5. type Config struct{
  6. Peers []Peer
  7. }

在playground上的示例

英文:

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

  1. type Peer struct{
  2. Pid int
  3. Address string
  4. }
  5. type Config struct{
  6. Peers []Peer
  7. }

Example on play.

答案2

得分: 0

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

  1. type Peer struct {
  2. CustomId int `json:"pid"`
  3. CustomAddress string `json:"address"`
  4. }

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

英文:

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

  1. type Peer struct{
  2. CustomId int `json:"pid"`
  3. CustomAddress string `json:"address"`
  4. }

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:

确定