Jeffail/gabs

floating point numbers

korpa opened this issue · 1 comments

korpa commented

Hi @Jeffail,

me again :) I have the problem that json.Unmarshal creates floating point numbers from long numbers. I use following function when decoding static json to prevent this problem:

//JSONDecode decodes json long numbers not as floating point numbers
func JSONDecode(response string) (map[string]interface{}, error) {

    /**
     * Instead of json.Unmarshal 
     * use this:
     * http://stackoverflow.com/questions/22343083/json-marshaling-with-long-numbers-in-golang-gives-floating-point-number
     * json.Unmarshal converts long numbers to 1.0e+07
     * UseNumber() does the trick here
     */

    var result map[string]interface{}
    d := json.NewDecoder(strings.NewReader(response))
    d.UseNumber()
    if err := d.Decode(&result); err != nil {
        Trace(err)
        return nil, err
    }
    return result, nil
}

Any chance to integrate this into gabs?

Hey @korpa,

I'm on a laptop where I can't test so take this with a pinch of salt, but I believe it can be done like this (not particularly simple I know):

    var result map[string]interface{}

    d := json.NewDecoder(strings.NewReader(`{"data":"test"}`))
    d.UseNumber()
    if err := d.Decode(&result); err != nil {
        panic(err)
    }

    g, err := gabs.Consume(result)
    if err != nil {
        panic(err)
    }

    fmt.Printf("JSON Data: %v\n", g.Path("data"))

I have thought about this in the past and concluded that I'd rather see gabs used to consume converted maps where the non default json decoding is needed rather than duplicate the API for NewDecoder within gabs.

This particular case (where we want to prevent floating numbers) is a very common problem, however, so if lots of people are having to write the above where they otherwise wouldn't I'd be happy to add something in.