Golang:使用字符串作为键解组以下 json 的最佳方法

Golang : best way to unmarshal following json with string as keys

我 json 喜欢

{
  "api_type" : "abc",
  "api_name" : "xyz",
  "cities" : {
    "new_york" : {
        "lat":"40.730610",
        "long":"-73.935242"
    },
    "london" : {
        "lat":"51.508530",
        "long":"-0.076132"
    },
    "amsterdam" : {
        "lat":"52.379189",
        "long":"4.899431"
    }

    //cities can be multiple
  }
}

我可以使用以下结构解组

type MyJsonName struct {
    APIName   string `json:"api_name"`
    APIType   string `json:"api_type"`
    Locations struct {
        Amsterdam struct {
            Lat  string `json:"lat"`
            Long string `json:"long"`
        } `json:"amsterdam"`
        London struct {
            Lat  string `json:"lat"`
            Long string `json:"long"`
        } `json:"london"`
        NewYork struct {
            Lat  string `json:"lat"`
            Long string `json:"long"`
        } `json:"new_york"`
    } `json:"locations"`
}

但是我的城市名称和数字在每次响应中都会不同,解组这种类型的 json 的最佳方法是什么,其中键可以是变化的字符串。

我会把 locations 做成一张地图(尽管你在 JSON 中把它叫做 cities):

type MyJsonName struct {
        APIName   string `json:"api_name"`
        APIType   string `json:"api_type"`
        Locations map[string]struct {
                Lat  string
                Long string
        } `json:"locations"`
}