1

this following code is working successfully, it converts my json file into a csv file. But I would like to add titles to each of my columns into the csv file. Unfortunately, I can't find out how to do that. If anyone has an idea it would be very helpful.

Regards

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")

}

1 Answer 1

2

Well if you want it just for this example can you just write the column headers to the file before the for statement, that is:

w := csv.NewWriter(csvdatafile)
//new code 
var header []string
header = append(header, "Number")
header = append(header, "Message")
header = append(header, "Name")
header = append(header, "Craft")
w.Write(header)

for _, obj := range general.People {   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.