gpt4 book ai didi

json - 如何在 go lang 中对 map[string]interface{} 类型进行多重排序?

转载 作者:数据小太阳 更新时间:2023-10-29 03:16:57 26 4
gpt4 key购买 nike

场景:假设我有一个 JSON 数据要在 go lang 中处理现在我正在使用 map[string]interface{} 类型,通过执行 marshal/unmarshal

使用 package encoding/json

下面是JSON数据:

{
"MysoreCity": {
"Population": 1000,
"VehicleCount": 1700,
"Temperature": 33
},
"BangaloreCity": {
"Population": 1000,
"VehicleCount": 3500,
"Temperature": 33
},
"KolarCity": {
"Population": 1250,
"VehicleCount": 3500,
"Temperature": 31
},
"TumkurCity": {
"Population": 800,
"VehicleCount": 300,
"Temperature": 29
}
}

现在我想根据优先级进行多排序降序,比如优先级是TemperaturePopulationVehicleCount 然后我希望输出像

{
"BangaloreCity": {
"Population": 1000,
"VehicleCount": 3500,
"Temperature": 33
},
"MysoreCity": {
"Population": 1000,
"VehicleCount": 1700,
"Temperature": 33
},
"KolarCity": {
"Population": 1250,
"VehicleCount": 3500,
"Temperature": 31
},
"TumkurCity": {
"Population": 800,
"VehicleCount": 300,
"Temperature": 29
}
}

因此根据一些动态优先级进行排序。

问题:我不知道如何在 go lang 中对其进行排序。我是 go lang 的新手,在搜索对我的数据进行排序时发现了一些东西;如下所述(来源:link)

When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next.

问题:谁能阐明如何对类似的 JSON 数据进行这种排序?

最佳答案

这个答案更多的是关于解决这个问题的方法,而不是具体的解决方案。我认为此时您更需要它,因为您还没有接近实际的解决方案。以下是简单的程序步骤;

1) 为此定义一个类型,从这里开始我将其称为City

"TumkurCity": {
"Population": 800,
"VehicleCount": 300,
"Temperature": 29
}

type City struct {
Population int
VehicleCount int
Temperature int
Name string
}

2) 解码为 map[string]City

3) 使用这样的方法来转换数据;

func ToSlice(m map[string]City) []City {
cities := make([]City, 0, len(m))
for k, v := range m {
v.Name = k
cities = append(cities, v)
}
return cities
}

4) 定义一些方法来根据需要对城市进行排序

我在浏览器中编写了该代码,所以它还没有经过测试或其他任何东西。它应该提供一个足够的例子来说明如何处理它。当您解码时,您的城市类型将没有名称值,因此您可以稍后将键(城市名称)分配给它。将它们放入 slice 或数组中,然后对其进行排序。如果您按照这些步骤操作,会非常简单。

关于json - 如何在 go lang 中对 map[string]interface{} 类型进行多重排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29536345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com