dongxue9997
2016-04-20 18:21
浏览 199

在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

图片转代码服务由CSDN问答提供 功能建议

我有一个示例json,字段名称并不是很重要,但是其中的嵌套值和数据类型 字段是。 我了解,在使用csv.Writer时,必须确保在写入csv时,数据是字符串数据类型。 我的问题是,写嵌套值的正确方法是什么?有没有一种有效的方法可以通过遍历整个json来转换所有非字符串值?

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

示例json

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doulangqiao854843 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
    
    点赞 打赏 评论

相关推荐 更多相似问题