Go-在json.Marshal中自动将字符串值转换为int值
我有[]映射[string]字符串。存在的值可以是整数(字符串形式)“1”。我想自动转换为int值,如1 例如:Go-在json.Marshal中自动将字符串值转换为int值,json,dictionary,go,marshalling,Json,Dictionary,Go,Marshalling,我有[]映射[string]字符串。存在的值可以是整数(字符串形式)“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
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"}}
如何实现这一点。您可以创建一个自定义类型,并在该类型上实现json.Marshaller接口。该方法实现可以透明地进行字符串->整数转换:
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))
您可以创建一个自定义类型,并在该类型上实现json.Marshaller接口。该方法实现可以透明地进行字符串->整数转换:
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))
无法将字符串自动转换为int。您应该解析这些值,然后将它们转换为int。无法自动将字符串转换为int。您应该解析这些值,然后将它们转换为int。