在Go中解析JSON的’NaN’值

huangapple go评论87阅读模式
英文:

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 -->

{&quot;backoff&quot;: NaN, &quot;cookie&quot;: &quot;&quot;, &quot;probabilities&quot;: [], &quot;words&quot;: []}

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(&quot;:NaN&quot;), []byte(&quot;:null&quot;), -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.

huangapple
  • 本文由 发表于 2014年7月29日 04:06:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/25003432.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定