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 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计