简体   繁体   English

Go-在json.marshal中自动将字符串值转换为int值

[英]Go - convert string value to int value automatically in json.Marshal

I have []map[string]string.Values present can be integer(in string form) "1".I want to automatically convert to int value like 1. 我有[] map [string] string。当前值可以是整数(以字符串形式)“ 1”。我想自动转换为类似1的int值。

Example: 例:

map1 := []map[string]string{
    {"k1": "1", "k2": "some value"},
    {"k1": "-12", "k2": "some value"},
}

I want to convert it to json like this using json.marshal 我想使用json.marshal将其转换为json

 {{"k1":1,"k2":"some value"}{"k1":-12,"k1":"some value"}}

How do I achive this. 我如何做到这一点。

You can create a custom type, and implement the json.Marshaller interface on that type. 您可以创建一个自定义类型,并在该类型上实现json.Marshaller接口。 That method implementation can transparently do the string -> int conversion: 该方法实现可以透明地执行字符串-> 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)
}

To use it, something like: 要使用它,类似:

values := []map[string]string{
    {"k1": "1", "k2": "somevalue"},
}

json.Marshal(IntValueMarshal(values))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM