Could not parse this json file in golang

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

{
    "peers": [
        {
            "pid": 1,
            "address": "127.0.0.1:17001"
        },
        {
            "pid": 2,
            "address": "127.0.0.1:17002"
        }
    ]
}

What can I do so far, 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)
}

The above code works for non-nested json files, such as the following:

{
    "pid": 1,
    "address": "127.0.0.1:17001"
}

But even after the change Config structso many times. I cannot parse the json file mentioned at the beginning of the question. Can someone please tell me how to proceed?

+4
source share
2 answers

You can use the following structure definition to display the JSON structure:

type Peer struct{
    Pid int
    Address string
}

type Config struct{
    Peers []Peer
}

An example of a game .

+8
source

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

type Peer struct{
        CustomId int 'json:"pid"' 
        CustomAddress string 'json:"address"'
    }
0
source

Source: https://habr.com/ru/post/1524477/


All Articles