我正在嘗試解析嵌入式 JSON 數(shù)組中的第一條記錄,并基于這些屬性的子集創(chuàng)建一個對象。我有這個工作,但基于這個問題,我不得不認(rèn)為有一種更優(yōu)雅/更不脆弱的方式來做到這一點。有關(guān)更多背景信息,這是調(diào)用musicbrainz JSON Web 服務(wù)的結(jié)果集,我將第一條artists記錄視為我正在尋找的藝術(shù)家。JSON 的格式是這樣的:{ "created": "2014-10-08T23:55:54.343Z", "count": 458, "offset": 0, "artists": [{ "id": "83b9cbe7-9857-49e2-ab8e-b57b01038103", "type": "Group", "score": "100", "name": "Pearl Jam", "sort-name": "Pearl Jam", "country": "US", "area": { "id": "489ce91b-6658-3307-9877-795b68554c98", "name": "United States", "sort-name": "United States" }, "begin-area": { "id": "10adc6b5-63bf-4b4e-993e-ed83b05c22fc", "name": "Seattle", "sort-name": "Seattle" }, "life-span": { "begin": "1990", "ended": null }, "aliases": [], "tags": [] }, ...}這是我到目前為止的代碼。我希望能夠使用我的ArtistCollection類型來解決一些問題interface{},但我不知道如何使用。我也不想費心映射藝術(shù)家記錄的所有屬性,我只對"name"和"id"值感興趣。package mainimport ( "fmt" "encoding/json" )type Artist struct { Id string Name string}type ArtistCollection struct { Artists []Artist}func main() { raw := //json formatted byte array var topLevel interface{} err := json.Unmarshal(raw, &topLevel) if err != nil { fmt.Println("Uh oh") } else { m := topLevel.(map[string]interface{}) //this seems really hacky/brittle, there has to be a better way? result := (m["artists"].([]interface{})[0]).(map[string]interface{}) artist := new(Artist) artist.Id = result["id"].(string) artist.Name = result["name"].(string) fmt.Println(artist) }}
檢索嵌套 Json 數(shù)組的第一條記錄
慕桂英3389331
2021-08-23 15:43:47