7

I'm a newbie in Golang.

I'm going to create a list of dictionaries that is resizable (this is not static) with append some dict to the list. Then I want to write it on a file, but I was confused.

I want something like this:

[
 {"port": 161, "timeout": 1, "sleep_time": 5, "metrics": [
  {"tag_name": "output_current", "id": 3},
  {"tag_name": "input_voltage", "id": 2}
 ]},
 {"port": 161, "timeout": 1, "sleep_time": 4, "metrics": [
   {"tag_name": "destructor", "id": 10}
 ]}
]

[UPDATE]:

What is the .append() Python equivalent in Go language like the following code snippet?

list_ = []
dict_ = {"key": val}
list_.append(dict_)

I've found the answer to this section ([UPDATE]) by borrowing from this answer:

type Dictionary map[string]interface{}
data := []Dictionary{}
dict1 := Dictionary{"key": 1}
dict2 := Dictionary{"key": 2}
data = append(data, dict1, dict2)
8
  • 3
    Have you looked at slices and maps?
    – bereal
    Commented Dec 19, 2018 at 7:23
  • Yes, I did it. So does not exist list and dict in Golang? What is the equivalent in Go? Commented Dec 19, 2018 at 7:30
  • 1
    This is my slice, and this is my map. This is for list, and this is for dict. (sorry couldn't help it). Anyhow, "a list of dicts" translates to "a slice of maps" in Go (I'd also consider struct).
    – bereal
    Commented Dec 19, 2018 at 7:36
  • 2
    Please walk through the tour of Go it covers the append part, too.
    – bereal
    Commented Dec 19, 2018 at 7:37
  • 1
    Yes, it is possible. With a help from json and ioutil.
    – bereal
    Commented Dec 19, 2018 at 7:42

2 Answers 2

13

If you need the data to be stored in a slice of dictionary/key-value-based format, then using the combination of slice and map[string]interface{} is enough.

In this example below, I created a new type called Dictionary, to avoid writing too many map[string]interface{} syntax on composite literals.

type Dictionary map[string]interface{}

data := []Dictionary{
    {
        "metrics": []Dictionary{
            { "tag_name": "output_current", "id": 3 },
            { "tag_name": "input_voltage", "id": 2 },
        },
        "port":       161,
        "timeout":    1,
        "sleep_time": 5,
    },
    {
        "metrics": []Dictionary{
            { "tag_name": "destructor", "id": 10 },
        },
        "port":       161,
        "timeout":    1,
        "sleep_time": 4,
    },
}

However if your data structure is fixed, then I suggest to use a struct instead map. Below is an another example as above, using same dataset but leveraging struct instead of map:

type Metric struct {
    TagName string `json:"tag_name"`
    ID      int    `json:"id"`
}

type Data struct {
    Port      int      `json:"port"`
    Timeout   int      `json:"timeout"`
    SleepTime int      `json:"sleep_time"`
    Metrics   []Metric `json:"metrics"`
}

data := []Data{
    Data{
        Port:      161,
        Timeout:   1,
        SleepTime: 5,
        Metrics: []Metric{
            Metric{TagName: "output_current", ID: 3},
            Metric{TagName: "input_voltage", ID: 2},
        },
    },
    Data{
        Port:      161,
        Timeout:   1,
        SleepTime: 4,
        Metrics: []Metric{
            Metric{TagName: "destructor", ID: 10},
        },
    },
}

Update 1

To be able to write the data in JSON file, the particular data needs to be converted into JSON string first. Use json.Marshal() to do the conversion from map data (or struct object data) into JSON string format (in []byte type).

buf, err := json.Marshal(data)
if err !=nil {
    panic(err)
}

err = ioutil.WriteFile("fileame.json", buf, 0644)
if err !=nil {
    panic(err)
}

Then use ioutil.WriteFile() to write it into file.


If you somehow need to print the JSON data as a string, then cast the buf into string type.

jsonString := string(buf)
fmt.Println(jsonString)

Statements above will generate output below:

[{"port":161,"timeout":1,"sleep_time":5,"metrics":[{"tag_name":"output_current","id":"3"},{"tag_name":"input_voltage","id":"2"}]},{"port":161,"timeout":1,"sleep_time":4,"metrics":[{"tag_name":"destructor","id":"10"}]}]
5
  • Thanks for response +1, that makes sense. Commented Dec 19, 2018 at 8:10
  • So finally, How can I store this slice of maps (list of dicts) on a file? I tried it using this: ioutil.WriteFile("config.json", data, 0644) but I got this error: 'cannot use data (type []Dictionary) as type []byte in argument to ioutil.WriteFile ' How can I write this as s json file? Commented Dec 19, 2018 at 8:51
  • 1
    @BenyaminJafari please take a look at updated answer
    – novalagung
    Commented Dec 19, 2018 at 8:58
  • I'm going to accept this, with an edit about some redundant Dictionary- I hope you don't mind. Commented Dec 19, 2018 at 9:05
  • @BenyaminJafari np, glad it helps :-)
    – novalagung
    Commented Dec 19, 2018 at 9:08
5

So the types you are looking for are:

dict => map
list => slice

A simple example of a map looks like:

m:=map[string]int{
  "a": 1,
  "b": 2,
}

A simple example of a slice looks like:

var s []int
s = append(s, 1)
s = append(s, 2, 3)

So to put that together for your type:

[]map[string]interface{}{
    {
        "port":       161,
        "timeout":    1,
        "sleep_time": 5,
        "metrics": []map[string]interface{}{
            {"tag_name": "output_current", "id": "3"},
            {"tag_name": "input_voltage", "id": "2"},
        },
    },
    {
        "port":       161,
        "timeout":    1,
        "sleep_time": 4,
        "metrics": []map[string]interface{}{
            {"tag_name": "destructor", "id": "10"},
        },
    },
}
4
  • Thanks for the response. But I got this error: cannot use map[string]int literal (type map[string]int) as type map[string][]string in assignment in your simple example of map. Commented Dec 19, 2018 at 8:03
  • Change map[string]int to map[string][]string
    – poy
    Commented Dec 19, 2018 at 8:04
  • What's mean of interface? Is it that means any type? Commented Dec 19, 2018 at 8:05
  • 2
    An empty interface does (e.g., interface{}). Take a look at tour.golang.org/methods/14
    – poy
    Commented Dec 19, 2018 at 8:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.