dqtl46964 2014-01-30 10:54
浏览 49
已采纳

无法在golang中解析此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?

  • 写回答

2条回答 默认 最新

  • dongpu9852 2014-01-30 11:05
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?