0

I have []map[string]string.Values present can be integer(in string form) "1".I want to automatically convert to int value like 1.

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

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

How do I achive this.

1
  • There is no way you can convert a string to int automatically. You should parse those values and then convert them to int. Commented Jun 15, 2018 at 9:01

1 Answer 1

2

You can create a custom type, and implement the json.Marshaller interface on that type. That method implementation can transparently do the string -> int conversion:

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.