使用可变数量的相似字段取消激活JSON对象

时间:2018-02-13 23:31:55

标签: json go

我正在处理一个可以像这样吐出JSON的API:

{
    "artist_name": "Wilhelm Stenhammar",
    "artist_name:1": "Helsingborg Symphony Orchestra",
    "artist_name:10": "NDR Radiophilharmonie",
    "artist_name:11": "Malm\u00f6 Opera Orchestra",
    "artist_name:12": "Radio Filharmonisch Orkest Holland",
    "artist_name:13": "Symphony Orchestra Of Norrlands Opera",
    "artist_name:14": "Pilsen Philharmonic Orchestra",
    "artist_name:15": "Latvian National Symphony",
    "artist_name:16": "SWR Radiofunkorchester, Kaiserslauten",
    "artist_name:17": "Orquesta Sinf\u00f3nica de San Luis Potos\u00ed",
    "artist_name:2": "Arvo Volmer",
    "artist_name:3": "V\u00e4ster\u00e5s Symphony Orchestra",
    "artist_name:4": "G\u00e4vle Symphony Orchestra",
    "artist_name:5": "Royal Danish Orchestra",
    "artist_name:6": "Stuttgart Philharmonic Orchestra",
    "artist_name:7": "Turku Philharmonic Orchestra",
    "artist_name:8": "Gothenburg Opera Orchestra",
    "artist_name:9": "Moscow Symphony Orchestra",
    "artist_uri": "spotify:artist:6gfRaesyLupPd0gDQaLwJV",
    "artist_uri:1": "spotify:artist:0K2m2TlgHkcp32NAZV6Omw",
    "artist_uri:10": "spotify:artist:6i9KFEJuHq78nMsQxeB1vR",
    "artist_uri:11": "spotify:artist:2bgesrziKLjYqObZ1i6KpO",
    "artist_uri:12": "spotify:artist:4TlqQbYkCmCDsrlkI2a09s",
    "artist_uri:13": "spotify:artist:1sKkv2iobrvnJtPtLJABf4",
    "artist_uri:14": "spotify:artist:5DEoOcExTp3y8yRzBVG1Bw",
    "artist_uri:15": "spotify:artist:4WP9O07oZuFjNpaoo8ktCf",
    "artist_uri:16": "spotify:artist:0AgZxnsoQq8uKYQEDQnO9N",
    "artist_uri:17": "spotify:artist:5qXInUZHHgmah0TPvUuq4l",
    "artist_uri:2": "spotify:artist:5zZjojCwIPWfzXOtSKTa0W",
    "artist_uri:3": "spotify:artist:4OYpD0LcwEZb5BdhyeJ7zT",
    "artist_uri:4": "spotify:artist:2DMF5PvArh8PhpR1YRDBgv",
    "artist_uri:5": "spotify:artist:3JZPA9VxDLixJfKDNbmlbT",
    "artist_uri:6": "spotify:artist:2G3SGwAd7uOTVm1y4IijBg",
    "artist_uri:7": "spotify:artist:2yJX6ev7Io4KagCeNdXFBB",
    "artist_uri:8": "spotify:artist:6fqElxCA09nHlqdkzY1sN9",
    "artist_uri:9": "spotify:artist:0udLXDzunp4xQRWhMNQPci",   }
}

该对象有多个艺术家名称和每个名称的URI。在某些情况下,可能会有比这里的例子更多或更少的艺术家,包括最常见的只有1的情况。

{
    "artist_name": "Wilhelm Stenhammar",
    "artist_uri": "spotify:artist:6gfRaesyLupPd0gDQaLwJV",
}

什么是取消此对象以捕获所有可能数量的艺术家姓名和URI的最佳方法?最后,我想要一个带有Name和URI字段的Artist对象数组,而unmartialed数组应该反映JSON中艺术家的顺序。

1 个答案:

答案 0 :(得分:3)

你可以做的最简单的事情是将map[string]string解组并按原样使用它,但这是一个更简洁的事情你可以做:定义

type Artist struct {
    Name string
    URI string // could be *uri.URL instead
}

type Foo struct {
    Artists []Artist
}

然后编写一个func (f *Foo) UnmarshalJSON(data []byte) error {,将其解组为map[string]string,然后依次检查每对密钥。如果找到它们,它会附加到f.Artists,如果它没有,则会停止。