我有[] map [string] string.Values present可以是整数(以字符串形式)" 1"。我想自动转换为int值,如1。
示例:
map1 := []map[string]string{
{"k1": "1", "k2": "some value"},
{"k1": "-12", "k2": "some value"},
}
我想使用json.marshal
将其转换为json {{"k1":1,"k2":"some value"}{"k1":-12,"k1":"some value"}}
我如何实现这一点。
答案 0 :(得分:2)
您可以创建自定义类型,并在该类型上实现json.Marshaller接口。该方法实现可以透明地执行字符串 - > int转换:
type IntValueMarshal []map[string]string
func (ivms IntValueMarshal) MarshalJSON() ([]byte, error) {
// create a new map to hold the converted elements
mapSlice := make([]map[string]interface{}, len(ivms))
// range each of the maps
for i, m := range ivms {
intVals := make(map[string]interface{})
// attempt to convert each to an int, if not, just use value
for k, v := range m {
iv, err := strconv.Atoi(v)
if err != nil {
intVals[k] = v
continue
}
intVals[k] = iv
}
mapSlice[i] = intVals
}
// marshal using standard marshaller
return json.Marshal(mapSlice)
}
使用它,例如:
values := []map[string]string{
{"k1": "1", "k2": "somevalue"},
}
json.Marshal(IntValueMarshal(values))