Read json array with json.NewDecoder

Viewed 32

How do I get a json array (named list in the json file) to a list using json.NewDecoder? My struct looks like this:

type Config struct {
    Data1 struct {
        Host string `json:"host"`
        Port string `json:"port"`
    } `json:"data1"`

    Data2 struct {
        Host string `json:"host"`
        Port string `json:"port"`
    } `json:"data2"`

    List struct {
        Items []string
    } `json:"list"`
}

and I'm parsing like this:

jsonParser := json.NewDecoder(configFile)
jsonParser.Decode(&config)

my config.json looks like this

{
  "data1": {
    "host": "10.10.20.20",
    "port": "1234"
  },
  "data2": {
    "host": "10.10.30.30",
    "port": "5678"
  },
  "list": [
    "item 1",
    "item 2",
    "item 3",
    "item 4"
  ]
}

It's easy when the fields have names but I havn't figured out on how to get the information from the list...

1 Answers

I found a way to resolve your problom. here is the code:

package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

type ConfigWithoutList struct {
    Data1 struct {
        Host string `json:"host"`
        Port string `json:"port"`
    } `json:"data1"`

    Data2 struct {
        Host string `json:"host"`
        Port string `json:"port"`
    } `json:"data2"`
}

type Config struct {
    ConfigWithoutList
    List struct {
        Items []string
    } `json:"list"`
}

func (u *Config) UnmarshalJSON(data []byte) error {
    aux := struct {
        List []string `json:"list"`
        ConfigWithoutList
    }{}
    if err := json.Unmarshal(data, &aux); err != nil {
        return err
    }
    u.List = struct {
        Items []string
    }{
        Items: aux.List,
    }
    return nil
}

func main() {
    const jsonStream = `{
  "data1": {
    "host": "10.10.20.20",
    "port": "1234"
  },
  "data2": {
    "host": "10.10.30.30",
    "port": "5678"
  },
  "list": [
    "item 1",
    "item 2",
    "item 3",
    "item 4"
  ]
}
`
    config := Config{}
    jsonParser := json.NewDecoder(strings.NewReader(jsonStream))
    jsonParser.Decode(&config)

    fmt.Println(config.List) // output => {[item 1 item 2 item 3 item 4]}
}
Related