I'm trying to look if there's a way (easy way) to add a header to each array in JSON using encoding/json
with GO.
What I mean?
Want to have something like this:
{
"Dog":[
{
"breed":"Chihuahua",
"color":"brown"
},
{
"breed":"Pug",
"color":"white"
}
],
"Cat":[
{
"breed":"British",
"color":"white"
},
"breed":"Ragdoll",
"color":"gray"
}
]
}
The main idea is to have a "category" in this case Dog
and Cat
.
I already have this solution but I'm looking for something that can Improve this.
My code looks like this:
type Dog struct {
Breed string
Color string
}
type Cat struct {
Breed string
Color string
}
func main(){
dogs := [...]Dog{
{"Chihuahua", "brown"},
{"Pug", "white"},
}
cats := [...]Cat{
{"British", "white"},
{"Ragdoll", "gray"},
}
c, err := json.MarshalIndent(cats, "", "\t")
if err != nil {
log.Fatal(err)
}
d, err := json.MarshalIndent(dogs, "", "\t")
if err != nil {
log.Fatal(err)
}
fmt.Println("{")
fmt.Printf(" \"Dog\": %v,
", string(d))
fmt.Printf(" \"Cat\": %v
}", string(c))
}
The main idea is to have "Dog" and "Cat" as new array but I want to improve my code to don't have it that "hardcoded" to looks as supposed to be, I'm wondering if there's an easy way to add the header "Dog" and all the array values, add the header "Cat" and all the array values.