我不知道怎么問,所以我舉個例子問。
我有一些這樣的資料
{
..
"velocityStatEntries": {
"8753": {
"estimated": {"value": 23.0,"text": "23.0"},
"completed": {"value": 27.0,"text": "27.0"}
},
"8673": {
"estimated": {"value": 54.5,"text": "54.5"},
"completed": {"value": 58.5,"text": "58.5"}
},
.
.
.
}
..
}
我想宣告一個型別,它將映射鍵作為它的“KEY”或我給定的任何屬性。是否可以不使用地圖迭代?
預期輸出:
{...
"velocityStatEntries": {
{
"key": "8753",
"estimated": {"value": 54.5,"text": "54.5"},
"completed": {"value": 58.5,"text": "58.5"}
},
{
"key": "8673",
"estimated": {"value": 54.5,"text": "54.5"},
"completed": {"value": 58.5,"text": "58.5"}
},
}
...
}
這就是我所做的
type VelocityStatEntry struct {
Key string
Estimated struct {
Value float64 `json:"value"`
Text string `json:"text"`
} `json:"estimated"`
Completed struct {
Value float64 `json:"value"`
Text string `json:"text"`
} `json:"completed"`
}
type RapidChartResponse struct {
...
VelocityStatEntries map[string]VelocityStatEntry `json:"velocityStatEntries"`
..
}
但它不起作用。我想將該字串映射鍵帶到 KEY 屬性。
uj5u.com熱心網友回復:
如果資料來自 JSON,那么您應該跳過map[string]interface{}并使用由您想要的結構實作的自定義解組器來執行您想要的操作。也許通過利用map[string]json.RawMessage. 但是map[string]interface{}結構轉換很痛苦,如果可能的話,避免它。
例如:
type VelocityStatEntryList []*VelocityStatEntry
func (ls *VelocityStatEntryList) UnmarshalJSON(data []byte) error {
var m map[string]json.RawMessage
if err := json.Unmarshal(data, &m); err != nil {
return err
}
for k, v := range m {
e := &VelocityStatEntry{Key: k}
if err := json.Unmarshal([]byte(v), e); err != nil {
return err
}
*ls = append(*ls, e)
}
return nil
}
https://go.dev/play/p/VcaW_BWXRVr
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/405669.html
標籤:
上一篇:獲取結構資訊
