2 回答
TA贡献1816条经验 获得超6个赞
始终检查错误很重要;如果您将代码更改为:
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
}
看起来您在某些时候对 the 有正确的想法,[]People但随后将其注释掉。
如果你取消注释[]People,解组为General(而不是[]General)然后让你的循环for _, obj := range general.People {它应该按预期工作。这假设您要遍历人员;general.Message 和 general.Number 也可用(但您不需要循环来访问这些)。
TA贡献1827条经验 获得超8个赞
你可以尝试这样的事情:
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
)
type People struct {
Name string
Craft string
}
type Response struct {
People []People
Number int
Message string
}
func main() {
// Reading data from JSON File
r, err := http.Get("http://api.open-notify.org/astros.json")
if err != nil {
fmt.Printf("The Http request failed with error %s\n", err)
}
var response Response
err = json.NewDecoder(r.Body).Decode(&response)
if err != nil {
fmt.Printf("decoding error%s\n", err)
return
}
// 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 response.People {
fmt.Println("Are you going into the for ?")
var record []string
//record = append(record, obj.People)
record = append(record, strconv.Itoa(response.Number), response.Message)
record = append(record, obj.Name)
// record = append(record, []string{obj})
w.Write(record)
fmt.Println("Are you coming here")
record = nil
}
w.Flush()
fmt.Println("Appending succed")
}
- 2 回答
- 0 关注
- 209 浏览
添加回答
举报