How to convert numerical value to json in GoLang

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

How to convert numerical value to json in GoLang

问题

我有一个计算总分的 Go 容器,它运行得很完美。

为了让我的代理文件能够读取它,我需要将返回值转换为 JSON。

我尝试了以下代码,但它没有起作用:

// 计算总分
marksSum := 0
for _, mark := range marks {
    marksSum += mark
}

j, _ := json.Marshal(markSum)

return j

非常感谢任何帮助!

英文:

I have a Go container that calculates the total marks scored, and works perfectly.

For this to be able to be read by my proxy file, i need the return value to be json.

I am trying this however it isnt working:

// Find the total grade
	marksSum := 0
	for _, mark := range marks {
		marksSum += mark
	}
	
	j, _ := json.Marshal(markSum)
	
	return j

Any help is much appreciated!

答案1

得分: 3

你可以创建一个结构体来定义你想要构建的 JSON 对象的结构(变量名应以大写字母开头)。

type Response struct {
    Error      error  `json:"error"`
    Input_text string `json:"string"`
    Answer     int    `json:"answer"`
}

然后使用上述结构体创建一个响应。

func main() {
    marks := []int{1, 2, 3, 4}

    marksSum := 0
    input := ""
    for _, mark := range marks {
        input = fmt.Sprintf("%s %d", input, mark)
        marksSum += mark
    }

    resp := &Response{
        Error:      nil,
        Input_text: input,
        Answer:     marksSum,
    }

    j, err := json.Marshal(resp)
    if err != nil {
        fmt.Printf("Errr : %v", err)
        return
    }

    fmt.Println(string(j))
}

你可以在这里查看代码的运行结果:https://go.dev/play/p/iC484GS7GKS

英文:

You can create a struct of how you want to structure your JSON object.(variable names should start with a capital letters)

type Response struct {
	Error      error  `json:"error"`
	Input_text string `json:"string"`
	Answer     int    `json:"answer"`
}

Then just create a response using the above struct.

func main() {
	marks := []int{1, 2, 3, 4}

	marksSum := 0
	input := ""
	for _, mark := range marks {
		input = fmt.Sprintf("%s %d", input, mark)
		marksSum += mark
	}

	resp := &Response{
		Error:      nil,
		Input_text: input,
		Answer:     marksSum,
	}

	j, err := json.Marshal(resp)
	if err != nil {
		fmt.Printf("Errr : %v", err)
		return
	}

	fmt.Println(string(j))
}

https://go.dev/play/p/iC484GS7GKS

huangapple
  • 本文由 发表于 2022年9月5日 22:49:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/73611189.html
匿名

发表评论

匿名网友

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

确定