I have the following data struct to build and send data in it. Then convert it to json and write a file. I need an array. Its element is a map. map["targets"]
value is an array and map["labels"]
is another map. How to build the complex data struct?
[
{
"targets": ["10.11.150.1:7870", "10.11.150.4:7870"],
"labels": {
"job": "mysql"
}
},
{
"targets": ["10.11.122.11:6001", "10.11.122.15:6002"],
"labels": {
"job": "postgres"
}
}
]
~
So your struct would look like this:
type Obj struct {
Targets []string `json:"targets"`
Labels map[string]string `json:"labels"`
}
Populate it:
obj := []Obj{
Obj{
Targets: []string{"10.11.150.1:7870", "10.11.150.4:7870"},
Labels: map[string]string{
"job": "mysql",
},
},
Obj{
Targets: []string{"10.11.122.11:6001", "10.11.122.15:6002"},
Labels: map[string]string{
"job": "postgres",
},
},
}
Marshal it to a string:
jsonBytes, err := json.Marshal(obj)
if err != nil {
log.Fatal("error marshaling struct to JSON:", err)
}
Write it to a file:
if err := ioutil.WriteFile("output.json", jsonBytes, 0644); err != nil {
log.Fatal("error writing file:", err)
}
Here’s everything all together:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
)
type obj struct {
Targets []string `json:"targets"`
Labels map[string]string `json:"labels"`
}
func main() {
obj := []obj{
obj{
Targets: []string{"10.11.150.1:7870", "10.11.150.4:7870"},
Labels: map[string]string{
"job": "mysql",
},
},
obj{
Targets: []string{"10.11.122.11:6001", "10.11.122.15:6002"},
Labels: map[string]string{
"job": "postgres",
},
},
}
jsonBytes, err := json.Marshal(obj)
if err != nil {
log.Fatal("error marshaling struct to JSON:", err)
}
if err := ioutil.WriteFile("output.json", jsonBytes, 0644); err != nil {
log.Fatal("error writing file:", err)
}
fmt.Printf("%+v
", jsonBytes)
}
This example can help you:
package main
import (
"fmt"
"encoding/json"
"io/ioutil"
)
type Object struct {
Targets []string `json:"targets"`
Labels Label `json:"labels"`
}
type Label struct {
Job string `json:"job"`
}
type Objects []Object
func main() {
objs := Objects{
{
Targets: []string{"10.11.150.1:7870", "10.11.150.4:7870"},
Labels: Label{Job: "mysql"},
},
{
Targets: []string{"10.11.122.11:6001", "10.11.122.15:6002"},
Labels: Label{Job: "postgres"},
},
}
bytes, err := json.Marshal(objs)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(bytes))
// 0644 is the file mode: https://golang.org/pkg/os/#FileMode
if err := ioutil.WriteFile("objs.json", bytes, 0644); err != nil {
fmt.Println(err)
}
}
More information: Converting Go struct to JSON, Go by Example: Writing Files