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.
There is no need to create json objects separately for dogs and cats. This will lead to separate json objects when marhsalling the data.
The approach you are trying is basically in appropriate and useless.
Approach should to create a result struct which will have dogs and cats structs as fields with type as slice of both of them respectively. Take for an example:
package main
import (
"fmt"
"encoding/json"
"log"
)
type Result struct{
Dog []Dog
Cat []Cat
}
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"},
}
result := Result{
Dog: dogs,
Cat: cats,
}
output, err := json.MarshalIndent(result, "", "\t")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(output))
}
Output:
{
"Dog": [
{
"Breed": "Chihuahua",
"Color": "brown"
},
{
"Breed": "Pug",
"Color": "white"
}
],
"Cat": [
{
"Breed": "British",
"Color": "white"
},
{
"Breed": "Ragdoll",
"Color": "gray"
}
]
}
Working Code on Go playground