gpt4 book ai didi

json - 如何在 Golang 中创建字典列表?

转载 作者:IT王子 更新时间:2023-10-29 01:19:15 27 4
gpt4 key购买 nike

我是 Golang 的新手。

我将创建一个可调整大小的字典列表(这不是静态的),并将一些 dict 附加到 list。然后我想把它写在一个文件上,但是我很困惑。

我想要这样的东西:

[
{"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}
]}
]

[更新]:

像下面的代码片段,Go 语言中的 .append() Python 等价物是什么?

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

我借用 this answer 找到了这部分的答案([更新]) :

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

最佳答案

如果您需要将数据存储在基于字典/键值格式的 slice 中,那么使用 slice 和 map[string]interface{} 的组合就足够了。

在下面的这个例子中,我创建了一个名为 Dictionary 的新类型,以避免在复合文字上编写过多的 map[string]interface{} 语法。

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,
},
}

但是,如果您的数据结构是固定的,那么我建议使用结构代替 map。下面是另一个与上面相同的示例,使用相同的数据集但利用结构而不是 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},
},
},
}

更新 1

为了能够在 JSON 文件中写入 data,需要先将特定的 data 转换为 JSON 字符串。使用 json.Marshal()map 数据(或结构对象数据)转换为 JSON 字符串格式([]byte 类型).

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

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

然后使用ioutil.WriteFile()将其写入文件。


如果您需要以某种方式将 JSON 数据打印为字符串,请将 buf 转换为 string 类型。

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

上面的语句将生成下面的输出:

[{"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"}]}]

关于json - 如何在 Golang 中创建字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53846350/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com