I'm new to Go and Json, so I might miss a lot of points here.
So what I'm basically trying to do is making a program which performs the simple Fizz-Buzz program and make a JSON out of it. This program takes two integers (a and b), iterate from a to b (i) and outputs:
Using this simple code snippet:
func fizzbuzz(a int, b int) string{
str := fmt.Sprint("{\"output\":[")
for i := a ; i <= b; i++ {
if i%5 == 0 && i%3 == 0 {str = fmt.Sprint(str, "\"FizzBuzz\"")
}else if i%3 == 0 {str = fmt.Sprint(str, "\"Fizz\"")
}else if i%5 == 0 {str = fmt.Sprint(str, "\"Buzz\"")
}else {str = fmt.Sprint(str, i)}
str = str + ","
}
str = str[:len(str) - 1]
str = str + "]}"
return str
}
I was able to construct the string that can later on be converted to JSON:
{"output":["FizzBuzz",1,2,"Fizz",4,"Buzz","Fizz",7,8,"Fizz","Buzz",11,"Fizz",13,14,"FizzBuzz"]}
This works fine so far. I'm just wondering, are there any other solutions to making a JSON array of mixed type (integer and strings) on Golang? I've tried struct and marshaling, but a struct seems to have fixed structure.
There are two good options that come to mind.
You can use an interface type.
package main
import (
"encoding/json"
"os"
)
type output struct {
Output []interface{} `json:"output"`
}
func main() {
out := output{
Output: []interface{}{"FizzBuzz", 1, 2, "Fizz"},
}
d, _ := json.Marshal(out)
os.Stdout.Write(d)
}
Output:
{"output":["FizzBuzz",1,2,"Fizz"]}
Or you can use a different JSON library, like gojay, which has a different API for serializing JSON.