【问题标题】:Marshalling jSON big ints turn into floats to the power编组 JSON 大整数变成浮点数
【发布时间】:2015-05-28 06:49:27
【问题描述】:

我有这条数据:

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
}

...将一些int转换为float类型的幂。

Itoa 仍然只是一些测试,因为编组器无法执行 map[int]interface{}(索引值作为整数的列表)。我只是不明白为什么 int 值会更改为它们的“显示”值,而不是它们的纯值。

更新:我用map[string]int 尝试了“属性”,并且只有一个条目。结果还是一样:(

【问题讨论】:

  • 我现在无法确认.. 但从记忆中,marshaller 默认使用float64 作为接口中的所有数字。然后它会在某个时候调用String(),如果数字足够大,就会产生你看到的科学/E表示法。
  • 这不是很奇怪吗? (长)数字可能是 JSON 文件中最常见的值。我应该只 Itoa 所有整数吗? :P 当我的服务器上的请求负载变得更重时,这可能会降低我的性能。

标签: json types go marshalling


【解决方案1】:

您可以将 int64 编组为 json 中的字符串,以避免使用 string 标记转换为 float64

type T struct {
    Val int64 `json:"val,string"`
}
t := T{Val: math.MaxInt64}
j, _ := json.Marshal(t)
fmt.Println(string(j))
// {"val":"9223372036854775807"}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 2016-04-17
    相关资源
    最近更新 更多