2

The following code to un-marshall json data from from byte array changing the type of float value to int.

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    byt := []byte(`{"num":6.0}`)
    var dat map[string]interface{}
    fmt.Println(byt)

    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)
}

Here is the playground link: https://go.dev/play/p/60YNkhIUABU

Is there anyway to keep the type as it is?

1 Answer 1

5

The unmarshalled number already is a float64. You can check this by adding a line to the end of your playground example to print out the type of the data:

fmt.Printf("%T\n", dat["num"])

If you want to have this be more explicit, you could try changing the type of dat from map[string]interface{} to map[string]float64.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way that float64 keeps 6.0 as 6.0 as is. Becuase I am pushing this unmarshall data to elasticsearch and elasticsearch treating it as a int. So later on if I get something like decimal number elasticsearch is throwing an error.
Can you put an example of the code where you are using this data in your question? Probably you need to use some kind of format code, like fmt.Sprintf("%.2f", dat["num"]).

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.