英文:
Marshalling jSON big ints turn into floats to the power
问题
我有这段数据:
productID, err := products.Insert(map[string]interface{}{
"Properties": map[string]interface{}{
strconv.Itoa(propertyNameID): map[string]string{
"en": "Jeans Jersey",
"nl": "Broek Jersey",
},
strconv.Itoa(propertyColorID): propertyOptionRedID,
},
"Type": productTypeID,
"Propertyset": propertysetID,
"Active": true,
"EAN13": "1234567890123"})
所有的***ID
变量的类型都是int
。不幸的是,当我进行普通的编组时:
{
"Active":true,
"EAN13":"1234567890123",
"Properties":{
"2286408386526632249":{
"en":"Jeans Jersey",
"nl":"Broek Jersey"
},
"4750062295175300168":7.908474319828591e+18
},
"Propertyset":8.882218269088507e+18,
"Type":7.185126253999425e+18
}
... 一些整数被转换为幂的float
类型。
Itoa
仍然只是一些测试,因为编组器无法处理map[int]interface{}
(具有整数索引值的列表)。我只是不明白为什么int
值会被更改为它们的"display"值,而不是它们的纯值。
更新: 我尝试了使用map[string]int
和只有一个条目的"Properties"。结果仍然相同
英文:
I have this piece of data:
productID, err := products.Insert(map[string]interface{}{
"Properties": map[string]interface{}{
strconv.Itoa(propertyNameID): map[string]string{
"en": "Jeans Jersey",
"nl": "Broek Jersey",
},
strconv.Itoa(propertyColorID): propertyOptionRedID,
},
"Type": productTypeID,
"Propertyset": propertysetID,
"Active": true,
"EAN13": "1234567890123"})
All the ***ID
variables are of type int
. Sadly when I do a normal marshal:
{
"Active":true,
"EAN13":"1234567890123",
"Properties":{
"2286408386526632249":{
"en":"Jeans Jersey",
"nl":"Broek Jersey"
},
"4750062295175300168":7.908474319828591e+18
},
"Propertyset":8.882218269088507e+18,
"Type":7.185126253999425e+18
}
... the some ints are transformed into float
type to the power.
The Itoa
are still just some tests tho, because the marshaller can't do map[int]interface{}
(lists with index-values as integers). I just don't understand why the int
values get changed to their "display"-value, instead of their pure value.
Update: I tried "Properties" with map[string]int
and just one entry. Still the same result
答案1
得分: 3
你可以使用string
标签将int64类型的值转换为字符串,以避免在JSON中将其转换为float64类型。
type T struct {
Val int64 `json:"val,string"`
}
t := T{Val: math.MaxInt64}
j, _ := json.Marshal(t)
fmt.Println(string(j))
// {"val":"9223372036854775807"}
以上代码将输出{"val":"9223372036854775807"}
。
英文:
You can marshal an int64 as a string in json to avoid the conversion to a float64 by using the string
tag
type T struct {
Val int64 `json:"val,string"`
}
t := T{Val: math.MaxInt64}
j, _ := json.Marshal(t)
fmt.Println(string(j))
// {"val":"9223372036854775807"}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论