Golang:解析具有字符串作为键的以下 JSON 的最佳方法

huangapple go评论84阅读模式
英文:

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 map[string]struct {
		Lat  string `json:"lat"`
		Long string `json:"long"`
	} `json:"cities"`
}

但是我的城市名称和数量在每个响应中都会有所不同,有什么好的方法可以解析这种键可以变化的JSON数据呢?

英文:

I have json like

{
  "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
  }
}

I can use following struct to unmarshal

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"`
}

but my city names and numbers will be different in each response, what is a best way unmarshal this type of json where keys can be string which varies.

答案1

得分: 7

我会将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"`
}
英文:

I would make the locations a map (although you have it called cities in the JSON):

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

huangapple
  • 本文由 发表于 2016年3月30日 12:43:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/36299867.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定