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