Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert JSON to CSV?

Tags:

go

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
like image 637
ekanna Avatar asked May 10 '13 12:05

ekanna


People also ask

Can postman convert JSON to CSV?

Working with data files | Postman Learning CenterTo convert your JSON response to a csv format, you'll need to write the script. You can copy this test script inside and move it to your request's test script. Now, change the fileExtension to csv and then write your csv data that instead of the response body.


2 Answers

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()
}
like image 194
peterSO Avatar answered Nov 15 '22 05:11

peterSO


csv Writer's Write does not expect an []interface{} it expects a []string.

like image 33
Chris Farmiloe Avatar answered Nov 15 '22 07:11

Chris Farmiloe