我正在尝试解析嵌入式 JSON 数组中的第一条记录,并基于这些属性的子集创建一个对象。我有这个工作,但基于这个问题,我不得不认为有一种更优雅/更不脆弱的方式来做到这一点。有关更多背景信息,这是调用musicbrainz JSON Web 服务的结果集,我将第一条artists记录视为我正在寻找的艺术家。
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{},但我不知道如何使用。我也不想费心映射艺术家记录的所有属性,我只对"name"和"id"值感兴趣。
package main
import (
"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)
}
}
月关宝盒
相关分类