douzhigan1687 2016-10-17 04:40 采纳率: 0%
浏览 36
已采纳

Golang:JSON格式的字节片

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.

  • 写回答

1条回答 默认 最新

  • dqf42223 2016-10-17 05:07
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100