我正在尝试将此astros.json文件保存到csv文件中。

一切正常我没有任何错误,但是我的代码没有进入for循环。

因此,astros.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 {
        fmt.Println("Are you going into the for ?")
        var record []string
        //record = append(record, obj.People)
        record = append(record, strconv.Itoa(obj.Number), obj.Message)
        record = append(record, obj.Message)
        //record = append(record, []string{People})
        w.Write(record)
        fmt.Println("Are you coming here")
        record = nil
    }
    w.Flush()
    fmt.Println("Appending succed")

}

最佳答案

始终检查错误很重要;如果将代码更改为:

err = json.Unmarshal([]byte(data), &general)
if err != nil {
   fmt.Printf("Error in unmarshall %s\n", err)
   return
}

然后您会看到问题所在; json.Unmarshal返回cannot unmarshal object into Go value of type []main.General。这意味着general为nil,因此永远不会输入循环。

比较JSON时,其原因显而易见:
{
    "people": [{
            "name": "Christina Koch",
            "craft": "ISS"
        }, {
            "name": "Alexander Skvortsov",
            "craft": "ISS"
        }, {
            "name": "Luca Parmitano",
            "craft": "ISS"
        }, {
            "name": "Andrew Morgan",
            "craft": "ISS"
        }, {
            "name": "Oleg Skripochka",
            "craft": "ISS"
        }, {
            "name": "Jessica Meir",
            "craft": "ISS"
        }
    ],
    "number": 6,
    "message": "success"
}

有了变量,您就可以解组; []General,其中General是:
type General struct {
    //People []People
    Number int
    Message string
}

[]People的某个点上,您似乎有正确的主意,但随后将其注释掉。

如果取消注释[]People,则将其解编为General(而不是[]General),然后使您的循环for _, obj := range general.People {应该可以按预期工作。假设您要遍历整个人; general.Message和general.Number也可用(但是您不需要循环即可访问它们)。

请参阅this example(已删除文件操作,因为游乐场不支持该操作)。

关于json - 如何将JSON文件保存到csv中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59996152/

10-09 20:04