gpt4 book ai didi

戈朗 : JSON formatted byte slice

转载 作者:IT王子 更新时间:2023-10-29 02:33:05 26 4
gpt4 key购买 nike

我是 Go 的新手。目前我有两个数组,如下所示:

words: ["apple", "banana", "peach"]
freq: [2, 3, 1]

其中“freq”存储“words”中每个单词的计数。我希望将这两个数组组合成一个 Json 格式的字节 slice ,看起来像

[{"w":"apple","c":2},{"w":"banana","c":3},{"w":"peach","c":1}]

我怎样才能实现这个目标?

目前我已经声明了一个结构

type Entry struct {
w string
c int
}

当我循环遍历这两个数组时,我做了

  res := make([]byte, len(words))
for i:=0;i<len(words);i++ {
obj := Entry{
w: words[i],
c: freq[i],
}
b, err := json.Marshal(obj)
if err==nil {
res = append(res, b...)
}
}

return res // {}{}{}

这并没有给我想要的结果。任何帮助表示赞赏。提前致谢。

最佳答案

json.Marshal 需要导出结构字段。

您可以使用 json 标签让 json 带有小写字母键。

type Entry struct {
W string `json:"w"`
C int `json:"c"`
}

此外,使用 []Entry 生成输出 json 会更容易。 Sample code .

关于戈朗 : JSON formatted byte slice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40078599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com