英文:
Parsing JSON 'NaN' value in Go
问题
当我尝试从Microsoft Web Ngram API解析这个JSON对象时:
<!-- language: lang-js -->
{"backoff": NaN, "cookie": "", "probabilities": [], "words": []}
我得到了错误信息:"invalid character 'N' looking for beginning of value"。
我知道NaN不是有效的JSON,但这个数据不是我的,我需要一种解析它的方法。
在Go语言中有没有简单的方法可以做到这一点?
英文:
When I try and unmarshal this JSON object from the Microsoft Web Ngram API:
<!-- language: lang-js -->
{"backoff": NaN, "cookie": "", "probabilities": [], "words": []}
I get the error: "invalid character 'N' looking for beginning of value"
I know that NaN isn't valid JSON but the data isn't mine and I need a way to parse it.
Is there any easy way to do this in Go?
答案1
得分: 9
你可以将其替换为null(或0或其他可接受的值):
b, err := ioutil.ReadAll(resp)
// 检查错误
b = bytes.Replace(b, []byte(":NaN"), []byte(":null"), -1)
// json.Decode(b)
英文:
You could replace it with null (or 0 or whatever is acceptable):
b, err := ioutil.ReadAll(resp)
//check err
b = bytes.Replace(b, []byte(":NaN"), []byte(":null"), -1)
//json.Decode(b)
答案2
得分: 1
我创建了xhhuango/json来支持NaN、+Inf和-Inf。该包是从Golang SDK encoding/json分支出来的,因此使用方法与encoding/json完全相同。
英文:
I created xhhuango/json to support NaN, +Inf, and -Inf. The package forks from Golang SDK encoding/json, so the usage is completely the same as encoding/json.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论