我從服務(wù)收到具有此格式的 JSON。{ "result": { "bn05deh7jsm86gtlg2l0C": [ { "index_name": "BASE", "index_value": 4081512, "timestamp": "2019-11-05T13:20:00Z", "op_id": "A0000000001" }, ... ], "bn05deh7jsm86gtlg2lgC": [ { "index_name": "BASE", "index_value": 4728633, "timestamp": "2019-11-05T13:20:00Z", "op_id": "A0000000001" }, ... ], ... }}我需要的是將其轉(zhuǎn)換為像 []Measure 這樣的對(duì)象數(shù)組:type Measure struct { IndexName string `json:"index_name"` IndexValue uint32 `json:"index_value"` Timestamp time.Time `json:"timestamp"` OperationID string `json:"op_id"` Guid string `json:"guid"`}哪里Guid應(yīng)該有價(jià)值bn05deh7jsm86gtlg2l0C,bn05deh7jsm86gtlg2lgC等等。這是我的代碼:url := "https://myurl.com"req, err := http.NewRequest("GET", url, nil)if req != nil { req.Header.Set("Content-Type", "application/json")}resp, err := client.Do(req)if err != nil { log.Println(err) return nil}var measures []Measureerr = json.NewDecoder(resp.Body).Decode(&measures)if err != nil { log.Println(err)}我怎樣才能做到這一點(diǎn)?
2 回答

慕雪6442864
TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
解碼為與數(shù)據(jù)結(jié)構(gòu)匹配的類型:
var d struct{ Result map[string][]Measure }
err = json.NewDecoder(resp.Body).Decode(&d)
將該數(shù)據(jù)轉(zhuǎn)換為所需的結(jié)果:
var measures []Measure
for k, vs := range d.Result {
for _, v := range vs {
v.Guid = k
measures = append(measures, v)
}
}

Helenr
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊
您不能使用純編碼/json 來執(zhí)行此操作。Marstall 進(jìn)入地圖[string]測(cè)量
- 2 回答
- 0 關(guān)注
- 185 瀏覽
添加回答
舉報(bào)
0/150
提交
取消