dongzhong1891 2013-05-10 12:02
浏览 206
已采纳

如何将JSON转换为CSV?

How can I fix the error?

http://play.golang.org/p/0UMnUZOUHw

// JSON to CSV in Golang
package main

import (
    "encoding/csv"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

type Json struct {
    RecordID int64  `json:"recordId"`
    DOJ      string `json:"Date of joining"`
    EmpID    string `json:"Employee ID"`
}

func main() {
    // reading data from JSON File
    data, err := ioutil.ReadFile("./people.json")
    if err != nil {
        fmt.Println(err)
    }
    // Unmarshal JSON data
    var d []Json
    err = json.Unmarshal([]byte(data), &d)
    if err != nil {
        fmt.Println(err)
    }
    // Create a csv file
    f, _ := os.Create("./people.csv")
    defer f.Close()
    // Write Unmarshaled json data to CSV file
    w := csv.NewWriter(f)

    // How to proceed further?
    /* I am getting errors if i use below
    for _,obj := range d {
      var record []interface{}
      record = append(record, obj.RecordID)
      record = append(record, obj.DOJ)
      record = append(record, obj.EmpID)
      w.Write(record)
    }
    */
}

Error:

cannot use record (type []interface {}) as type []string in function argument
  • 写回答

2条回答 默认 最新

  • dongtong1226 2013-05-10 12:16
    关注

    For example,

    package main
    
    import (
        "encoding/csv"
        "encoding/json"
        "fmt"
        "io/ioutil"
        "os"
        "strconv"
    )
    
    type Json struct {
        RecordID int64  `json:"recordId"`
        DOJ      string `json:"Date of joining"`
        EmpID    string `json:"Employee ID"`
    }
    
    func main() {
        // reading data from JSON File
        data, err := ioutil.ReadFile("./people.json")
        if err != nil {
            fmt.Println(err)
        }
        // Unmarshal JSON data
        var d []Json
        err = json.Unmarshal([]byte(data), &d)
        if err != nil {
            fmt.Println(err)
        }
        // Create a csv file
        f, err := os.Create("./people.csv")
        if err != nil {
            fmt.Println(err)
        }
        defer f.Close()
        // Write Unmarshaled json data to CSV file
        w := csv.NewWriter(f)
        for _, obj := range d {
            var record []string
            record = append(record, strconv.FormatInt(obj.RecordID, 10))
            record = append(record, obj.DOJ)
            record = append(record, obj.EmpID)
            w.Write(record)
        }
        w.Flush()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?