Search code examples
jsongomarshalling

Writing a JSON of different types in Go (int and string)


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:

  • "Fizz" if the number is a factor of 3
  • "Buzz" if the number is a factor of 5
  • "FizzBuzz" if the number is a factor both and,
  • i if the number isn't a factor of both

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.


Solution

  • 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.