douyi1939 2014-09-16 20:34
浏览 195
已采纳

[] map [string] string到csv [] byte的惯用转换

I have a method which accepts an io.Reader in order to make an http POST (I can change this if needed) I will be submitted batches of x rows to this call method. I'm storing my rows as map[string]string for ease of checking that the keys are correct. What is the most streamlined way to submit a slice of map[string]string to that call method, which currently accepts a io.Reader?

  • 写回答

1条回答 默认 最新

  • doulangchao8934 2014-09-16 21:12
    关注

    Use the encoding/csv package to generate the CSV encoding. Here's how to encode to a []byte given column names:

    func encodeCSV(columns []string, rows []map[string]string) ([]byte, error) {
        var buf bytes.Buffer
        w := csv.NewWriter(&buf)
        if err := w.Write(columns); err != nil {
           return nil, err
        }
        r := make([]string, len(columns))
        for _, row :=  range rows {
           for i, column := range columns {
             r[i] = row[column]
           }
           if err := w.Write(r); err != nil {
              return nil, err
           }
        }
        if err := w.Flush(); err != nil {
           return nil, err
        }
        return buf.Bytes(), nil
     }
    

    Use bytes.NewReader to create the body for post:

    data, err := encodeCSV(coluns, rows)
    if err != nil {
       // handle error
    }
    req, err := http.NewRequest("POST", url, bytes.NewReader(data))
    

    If you have control over the data format, then consider using JSON:

    data, err := json.Marshal(rows)
    if err != nil {
        // handle error
    }
    req, err := http.NewRequest("POST", url, bytes.NewReader(data))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效