I'm new to Go. Currently I have two arrays that look like:
words: ["apple", "banana", "peach"]
freq: [2, 3, 1]
where "freq" stores the count of each word in "words". I hope to combine the two arrays into a Json formatted byte slice that looks like
[{"w":"apple","c":2},{"w":"banana","c":3},{"w":"peach","c":1}]
How can I achieve this goal?
Currently I've declared a struct
type Entry struct {
w string
c int
}
and when I loop through the two arrays, I did
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 // {}{}{}
which doesn't gives me the desired result. Any help is appreciated. Thanks in advance.
json.Marshal requires the struct fields to be exported.
You can use json tags to have json with small letter keys.
type Entry struct {
W string `json:"w"`
C int `json:"c"`
}
Also it would be easier to use a []Entry to generate the output json. Sample code.