以下代码运行成功,它将我的 json 文件转换为 csv 文件。但我想将我的每一列的标题添加到 csv 文件中。不幸的是,我不知道该怎么做。如果有人有想法,那将非常有帮助。


问候


package main


import (

    "encoding/json"

    "encoding/csv"

    "fmt"

    "io/ioutil"

    "os"

    "net/http"

    "strconv"

)


type People struct {

    Name string

    Craft string

}


type General struct {

    People []People

    Number int

    Message string

}


func main() {

    // Reading data from JSON File  

    response, err := http.Get("http://api.open-notify.org/astros.json")

    if err != nil {

        fmt.Printf("The Http request failed with error %s\n", err)

    }


    data,_ := ioutil.ReadAll(response.Body)

    //fmt.Println(string(data))

    // Unmarshal JSON data

    var general General

    json.Unmarshal([]byte(data), &general)

    //fmt.Printf("First person: %s, Message: %s", general.People[0].Name, general.Message)


    // Create a csv file

    csvdatafile, err := os.Create("./astros.csv")

    if err != nil {

        fmt.Println(err)

    }

    defer csvdatafile.Close()

    // Write Unmarshaled json data to CSV file

    w := csv.NewWriter(csvdatafile)

    for _, obj := range general.People {    

        fmt.Println("Are you going into the for ?")

        var record []string

        record = append(record, strconv.Itoa(general.Number), general.Message)

        record = append(record, obj.Name, obj.Craft)

        w.Write(record)

        fmt.Println("Are you coming here")

        record = nil

    }

    w.Flush()

    fmt.Println("Appending succed")


}