Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to parse this json file in golang

Tags:

json

go

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?

like image 796
santosh-patil Avatar asked Feb 14 '23 22:02

santosh-patil


1 Answers

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.

like image 140
nemo Avatar answered Mar 08 '23 06:03

nemo