json is string. like 10-->"10" //https://github.co" />
登录
首页 >  Golang >  Go问答 str:"10"-->

为什么在使用jsonpb时,int64被解码为字符串而不是数字。例如,int64 str=10 --> str:"10"

来源:stackoverflow

时间:2024-03-01 16:39:26 343浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《为什么在使用jsonpb时,int64被解码为字符串而不是数字。例如,int64 str=10 --> str:"10"》,聊聊,我们一起来看看吧!

问题内容

//code:630

//jsonpb, why int64 -> json is string. like 10-->"10"

//https://github.com/golang/protobuf/blob/master/jsonpb/jsonpb.go

// Default handling defers to the encoding/json library.
b, err := json.Marshal(v.Interface())
if err != nil {
    return err
}
needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64)
if needToQuote {
    out.write(`"`)
}
out.write(string(b))
if needToQuote {
    out.write(`"`)
}

问题:

为什么要在值周围附加“\'”?


解决方案


因为 JavaScript 中整数的表示方式意味着最大整数是 (2 的 53 次方)-1 (参见 https://stackoverflow.com/a/307200/1153938)

int64 中的最大整数大于此值,因此为了防止出现大整数的情况,库会改为使用数字字符串

由于 JavaScript 数字有符号,对于大负数也是如此

本篇关于《为什么在使用jsonpb时,int64被解码为字符串而不是数字。例如,int64 str=10 --> str:"10"》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>