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.

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

报告相同问题?

悬赏问题

  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源