2 回答

TA貢獻1820條經驗 獲得超9個贊
seriesLabels是一個 JSON 數組,其元素也是 JSON 數組。
要解析數組的 JSON 數組,您可以在 Go 中使用切片:
type Data struct {
SeriesLabels [][]interface{}
}
測試它:
var pw *PopularWord
if err := json.Unmarshal([]byte(src), &pw); err != nil {
panic(err)
}
fmt.Println(pw)
for _, sl := range pw.Data.SeriesLabels {
fmt.Println(sl)
}
輸出(在Go游樂場上嘗試):
&{0xc000120108}
[0 (none)]
[0 Cerveza]
[0 Cigarros]
[0 Tecate]
[0 Cafe]
[0 Amstel]
[0 Leche]
[0 Ultra]
[0 Coca cola]
[0 Agua]
要將內部數組作為結構值獲取,您可以實現自定義取消封接:
type Data struct {
SeriesLabels []*SeriesLabels `json:"seriesLabels"`
}
type SeriesLabels struct {
value int32
name string
}
func (sl *SeriesLabels) UnmarshalJSON(p []byte) error {
var s []interface{}
if err := json.Unmarshal(p, &s); err != nil {
return err
}
if len(s) > 0 {
if f, ok := s[0].(float64); ok {
sl.value = int32(f)
}
}
if len(s) > 1 {
if s, ok := s[1].(string); ok {
sl.name = s
}
}
return nil
}
測試代碼是相同的,輸出(在Go Playground上嘗試這個):
&{0xc0000aa0f0}
&{0 (none)}
&{0 Cerveza}
&{0 Cigarros}
&{0 Tecate}
&{0 Cafe}
&{0 Amstel}
&{0 Leche}
&{0 Ultra}
&{0 Coca cola}
&{0 Agua}

TA貢獻1839條經驗 獲得超15個贊
問題在于,在 JSON 中將其表示為數組。如果要使用 ,則必須實現取消marshaler接口對其進行解碼(否則它只會接受JSON對象)。SeriesLabelsencoding/json
幸運的是,代碼很簡單:
func (s *SeriesLabels) UnmarshalJSON(d []byte) error {
arr := []interface{}{&s.value, &s.name}
return json.Unmarshal(d, &arr)
}
請注意,此代碼將忽略無效輸入(數組太長或類型不正確)。根據您的需要,您可能希望在調用后添加檢查,以確保數組長度和內容(指針)未更改。json.Unmarshal
還有其他用于 Go 的 JSON 解析庫可以使其不那么麻煩,例如 gojay。
- 2 回答
- 0 關注
- 129 瀏覽
添加回答
舉報