Parsing JSON 'NaN' value in Go
Asked Answered
I

2

13

When I try and unmarshal this JSON object from the Microsoft Web Ngram API:

{"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?

Ivy answered 28/7, 2014 at 20:6 Comment(0)
W
8

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)
Wadley answered 28/7, 2014 at 20:16 Comment(1)
Hmm I thought that would be really slow but it only increases the runtime by 1.2-1.5x, which is completely fine. Cheers :)Ivy
I
1

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.

Irrespirable answered 15/9, 2022 at 4:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.