gpt4 book ai didi

go - 如何将 JSON 转换为 CSV?

转载 作者:IT王子 更新时间:2023-10-29 00:34:26 25 4
gpt4 key购买 nike

如何修复错误?

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)
}
*/
}

错误:

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

最佳答案

例如,

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()
}

关于go - 如何将 JSON 转换为 CSV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16481809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com