json.Marshal of generic interfaces: unexpected conversions

234 views
Skip to first unread message

pistacchio

unread,
Aug 6, 2010, 9:00:25 PM8/6/10
to golang-nuts
Hi,

I have a map[string]interface{} and I can't determine that type the
interface{} will be at runtime. I've serialized it with json.Marshal
and saved as a string (in a file).

If i serialize a int, it gets deserialized as float64 and this, of
course, rises casting problems. How can I work this out? The resulting
json is as simple as {"num":1}, so I guess that the problem only
emerges with numeric types. How come go interprets it as float64 and
not the most immediate int? How to manage the right (de)serialization
of ints, uints, floats and the like?

Thanks in advance.

Andrew Gerrand

unread,
Aug 8, 2010, 7:24:35 PM8/8/10
to pistacchio, golang-nuts

You can manage this by deserializing known data structures into actual structs:

package main

import (
"fmt"
"json"
)

type Data struct {
i int
f float
}

var j = `{"i": 1, "f": 2.5}`

func main() {
d := new(Data)
json.Unmarshal(j, d)
fmt.Println(d)
}

In this example, d.i and d.f will be of the correct types. Otherwise
json just guesses. (Although guessing float64 for "1" is not great.)

Andrew

Reply all
Reply to author
Forward
0 new messages