0

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.

2
  • Can you update with how you're using the for loo ? Also using a []Entry within the loop is better that appending to res. Commented Oct 17, 2016 at 5:00
  • @JohnSPerayil Updated. Commented Oct 17, 2016 at 5:04

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much sir!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.