dpkpaxhzffixp8426
2018-12-19 07:20
浏览 214

如何在Golang中创建词典列表?

I'm newbie with Golang.

I want to create a list of dictionaries with resizable capability (this is not static) with append some dict to the list, finally write it on a file, but I confused.

I want something like that:

[
 {"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 something like that?

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

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

type Dictionary map[string]interface{}
data := []Dictionary{}
dict1 := Dictionary{"key": 1}
dict2 := Dictionary{"key": 2}
data = append(data, dict1, dict2)

图片转代码服务由CSDN问答提供 功能建议

我是Golang的新手。

我要创建一个列表 具有可调整大小功能的字典(不是静态的),并将一些字典追加到列表中,最后将其写入文件中,但我感到困惑。

我想要这样的东西:

  [
 {“ 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,” 指标“:[
 {” tag_name“:”析构函数“,” id“:10} 
]} 
] 
   
 
 
< p> [UPDATE]:

Go语言中与 .append()类似的Python是什么?

  list_ = [] 
dict_ = {“ key”:val} 
list_.append(dict _)
   
 
 

我找到了本节的答案( [UPDATE]),借用此答案

 类型字典映射 [string]界面{} 
data:= [] D  ictionary {} 
dict1:=字典{“ key”:1} 
dict2:=字典{“ key”:2} 
data = append(data,dict1,dict2)
   
  
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douchengchu8374 2018-12-19 07:28
    已采纳

    If you need the data to be stored in a dictionary, using a 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,
        },
    }
    

    But I suggest, if your data structure is fixed, then define a struct instead. Below is an another example using same dataset but in struct object:

    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 data need to be converted into json string first. Use json.Marshal() to do the conversion from map data (or struct object data) to json string, 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 string, cast the buf into string type first.

    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"}]}]
    
    点赞 打赏 评论
  • duanmu0834 2018-12-19 07:33

    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"},
            },
        },
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题