Golang snippet: int64 that serializes into JSON as string

Posted on Oct 24, 2018

Because Javascript doesn’t support 64 bit integers (everything is stored as a float64), if you’re sending them as JSON in a JSON API response to the browser, you probably want to convert them to and from ints.

Here’s a type you can use in your structs or wherever to do this automatically when (un)marshalling JSON.

package utils

import (
    "encoding/json"
    "fmt"
    "strconv"
)

type ID int64

func (i ID) MarshalJSON() ([]byte, error) {
    return json.Marshal(fmt.Sprint(i))
}

func (i *ID) UnmarshalJSON(b []byte) error {
    var iStr string
    err := json.Unmarshal(b, &iStr)
    if err != nil {
        return err
    }

    val, err := strconv.ParseInt(iStr, 10, 64)
    if err != nil {
        return err
    }

    *i = ID(val)
    return nil
}