我怎麼會從下面JSON解析嵌套的JSON在去語言
這裏分析和提取某些值是樣本JSON響應
{"success":true,"endpoint":"https://api.abcxyz.com","info":
{"Guestconnected":134,"Guestratio":100000.06963,"symbol1":
{"code":"NY","symbol":"*","name":"newyear","codev":391.78161,"symbolAppearsAfter
":false,"local":true},"symbol2":
{"code":"HNY","symbol":"@","name":"HappyNewYear","codev":1000000.0960,"symbolApp
earsAfter":true,"local":false},"latest":
{"value":1597509,"autovalue":"00099cf8da58a36c08f2ef98650ff6043ddfb","height":47
4696,"time":1499527696}},"Allguest":
{"all":4,"filtered":4,"total_invitations":15430,"sent_invitations":15430,"final_
invitations":0},"Guestlist":
[{"GuestCode":"369AR","all":2,"total_invitations":5430,"sent_invitations":5430,"
final_invitations":0,"change":0,"accounts":0},
{"GuestCode":"6POIA96TY","all":2,"total_invitations":10000,"sent_invitations":10
000,"final_invitations":0,"change":0,"accounts":0}]}
我的代碼是:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type object struct {
Success bool `json:"success"`
Endpoint string `json:"endpoint"`
Allguest struct {
All int `json:"all"`
Filtered int `json:"filtered"`
TotalInvitations int `json:"total_invitations"`
SentInvitations int `json:"sent_invitations"`
FinalInvitations int `json:"final_invitations"`
} `json:"Allguest"`
Guestlist []struct {
GuestCode string `json:"GuestCode"`
All int `json:"all"`
TotalInvitations int `json:"total_invitations"`
SentInvitations int `json:"sent_invitations"`
FinalInvitations int `json:"final_invitations"`
Change int `json:"change"`
Accounts int `json:"accounts"`
} `json:"Guestlist"`
}
func main() {
uri := "https://siteurl.com/api?lists=1"
res, err := http.Get(uri)
fmt.Println(uri)
if err != nil {
fmt.Println("Error:", err)
log.Fatal(err)
}
defer res.Body.Close()
var s object
err := json.NewDecoder(res.Body).Decode(&s)
if err != nil {
log.Fatal(err)
fmt.Println("Error:", err)
}
fmt.Println(s.Success)
fmt.Println(s.Allguest.TotalInvitations)
for i := 0; i < 6; i++ {
fmt.Println(s.Guestlist[i].TotalInvitations)
)
}
問題是:
如果回覆爲空,則表明
index out of range error
我們該如何避免?應用條件,如果
TotalInvitations
值大於100
然後在100.csv
其他保存保存others.csv
@Nancyme您應該考慮查看[文檔的學習部分](https:// golang。org/doc /#learning)以及[探索核心軟件包](https://golang.org/pkg/)。你似乎不明白'* csv.Writer'的'Write'方法只接受'[] string',而不是'int'。您有正確的想法,但您需要確定要寫入文件的數據以及如何將該數據轉換爲一段字符串才能完成此操作。 –
像這樣'TotalInvites:= [] [] string {{s.Guestlist [i] .TotalInvitations}} – Nancyme
@Nancyme您不會將整數轉換爲'[] [] string'對象;你正在用一個整數作爲唯一的值創建一個新的[[] []字符串對象,這將不起作用,因爲'int'不是與'string'兼容的類型。學習,不要只是猜測。如果您遇到麻煩並且需要提出問題,我們會在這裏提供幫助,而不是教您使用整個語言;我在這個答案的最後評論中鏈接了學習資源。 –