英文:
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"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论