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

huangapple go评论77阅读模式
英文:

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

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对Go和Json都不太熟悉,所以可能会漏掉很多要点。

我基本上想做的是编写一个程序,执行简单的Fizz-Buzz程序,并将其转换为JSON格式。
这个程序接受两个整数(ab),从abi)进行迭代,并输出:

  • 如果数字是3的倍数,则输出"Fizz"
  • 如果数字是5的倍数,则输出"Buzz"
  • 如果数字既是3的倍数又是5的倍数,则输出"FizzBuzz"
  • 如果数字既不是3的倍数也不是5的倍数,则输出数字i

使用以下简单的代码片段:

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
}

我能够构建出一个字符串,稍后可以将其转换为JSON:

{"output":["FizzBuzz",1,2,"Fizz",4,"Buzz","Fizz",7,8,"Fizz","Buzz",11,"Fizz",13,14,"FizzBuzz"]}

到目前为止,这个方法运行良好。我只是想知道,在Golang中是否有其他方法可以创建一个包含混合类型(整数和字符串)的JSON数组?我尝试过使用结构体和marshaling,但结构体似乎具有固定的结构。

英文:

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(&quot;{\&quot;output\&quot;:[&quot;)
	for i := a ; i &lt;= b; i++ {
		if i%5 == 0 &amp;&amp; i%3 == 0 {str = fmt.Sprint(str, &quot;\&quot;FizzBuzz\&quot;&quot;)
		}else if i%3 == 0 {str = fmt.Sprint(str, &quot;\&quot;Fizz\&quot;&quot;)
		}else if i%5 == 0 {str = fmt.Sprint(str, &quot;\&quot;Buzz\&quot;&quot;)
		}else {str = fmt.Sprint(str, i)}
		str = str + &quot;,&quot;
	}
	str = str[:len(str) - 1]
	str = str + &quot;]}&quot;
	return str
}

I was able to construct the string that can later on be converted to JSON:

{&quot;output&quot;:[&quot;FizzBuzz&quot;,1,2,&quot;Fizz&quot;,4,&quot;Buzz&quot;,&quot;Fizz&quot;,7,8,&quot;Fizz&quot;,&quot;Buzz&quot;,11,&quot;Fizz&quot;,13,14,&quot;FizzBuzz&quot;]}

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.

答案1

得分: 1

有两个好的选择可以考虑。

你可以使用一个接口类型。

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":["FizzBuzz",1,2,"Fizz"]}

或者你可以使用一个不同的 JSON 库,比如 gojay,它有一个不同的 API 用于序列化 JSON。

英文:

There are two good options that come to mind.

You can use an interface type.

package main

import (
	&quot;encoding/json&quot;
	&quot;os&quot;
)

type output struct {
	Output []interface{} `json:&quot;output&quot;`
}

func main() {
	out := output{
		Output: []interface{}{&quot;FizzBuzz&quot;, 1, 2, &quot;Fizz&quot;},
	}
	d, _ := json.Marshal(out)
	os.Stdout.Write(d)
}

Output:

{&quot;output&quot;:[&quot;FizzBuzz&quot;,1,2,&quot;Fizz&quot;]}

Or you can use a different JSON library, like gojay, which has a different API for serializing JSON.

huangapple
  • 本文由 发表于 2021年10月5日 09:42:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/69444026.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定