dongxue9997 2016-04-20 18:21
浏览 285
已采纳

在GO中将嵌套的JSON转换为csv

I have an example json, the field names aren't really important but the nested values and the data types of some fields are. I understand that in go you have to make sure that when you write to a csv, the data is a string data type when you use csv.Writer. My question is, whats the proper way of writing the nested values, and is there an efficient way to convert all non-string values by iterating through the overall json?

`{
  "name":"Name1",
  "id": 2,
  "jobs":{
      "job1":"somejob",
      "job2":"somejob2"
   },
  "prevIds":{
      "id1": 100,
      "id2": 102
  }
}`

Is the example json

  • 写回答

1条回答 默认 最新

  • 普通网友 2016-04-20 19:19
    关注

    A working example is below:

    package main
    
    import (
        "encoding/csv"
        "encoding/json"
        "fmt"
        "log"
        "os"
        "strconv"
    )
    
    func decodeJson(m map[string]interface{}) []string {
        values := make([]string, 0, len(m))
        for _, v := range m {
            switch vv := v.(type) {
            case map[string]interface{}:
                for _, value := range decodeJson(vv) {
                    values = append(values, value)
                }
            case string:
                values = append(values, vv)
            case float64:
                values = append(values, strconv.FormatFloat(vv, 'f', -1, 64))
            case []interface{}:
                // Arrays aren't currently handled, since you haven't indicated that we should
                // and it's non-trivial to do so.
            case bool:
                values = append(values, strconv.FormatBool(vv))
            case nil:
                values = append(values, "nil")
            }
        }
        return values
    }
    
    func main() {
        var d interface{}
        err := json.Unmarshal(exampleJSON, &d)
        if err != nil {
            log.Fatal("Failed to unmarshal")
        }
        values := decodeJson(d.(map[string]interface{}))
        fmt.Println(values)
    
        f, err := os.Create("outputfile.csv")
        if err != nil {
            log.Fatal("Failed to create outputfile.csv")
        }
        defer f.Close()
        w := csv.NewWriter(f)
        if err := w.Write(values); err != nil {
            log.Fatal("Failed to write to file")
        }
        w.Flush()
        if err := w.Error(); err != nil {
            log.Fatal("Failed to flush outputfile.csv")
        }
    }
    
    var exampleJSON []byte = []byte(`{
      "name":"Name1",
      "id": 2,
      "jobs":{
          "job1":"somejob",
          "job2":"somejob2"
       },
      "prevIds":{
          "id1": 100,
          "id2": 102
      }
    }`)
    

    This works by decoding the arbitrary JSON as shown in this goblog post then iterating and handling each possible type by converting it to string in the usual way. If you come across a map[string]interface{}, then you're recursing to get the next set of data.

    Once you've got a []string, you can pass it to your csv.Writer to write out however you like. In this case the output is

    Name1,2,somejob,somejob2,100,102
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?