14

I'm trying to parse a json stream in Go. I've created a simplified example:

 package main
 import (
    "encoding/json"
    "fmt"
 )

 var d = []byte(`{ "world":[{"data": 2251799813685312}, {"data": null}]}`)

 type jsonobj struct{ World []World }
 type World struct{ Data int64 }

 func main() {
    var data jsonobj
    jerr := json.Unmarshal(d, &data)
    fmt.Println(jerr)
 }

this will give me

go run testmin.go
json: cannot unmarshal null into Go value of type int64

I've found a nullable int64 in the sql package, but json doesn't seem to be able to handle it.

Is there a nullable int64 type that json can handle? If possible I'd be happy with the json null being translated to, -1 or MinValue.

Thank you for your input, Fabian

2
  • Next time, the example can be shortened to var n int64 and json.Unmarshal("2251799813685312", &n) Commented Jun 14, 2012 at 6:54
  • just want you guys to know, tested with Go 1.1.2, "null" can be use with int type Commented Aug 29, 2013 at 3:56

2 Answers 2

30

Just use a *int64. A pointer can either be nil or it can point to an int64 with an associated value and they work fine with Go's JSON package.

Sign up to request clarification or add additional context in comments.

2 Comments

splendid! Thanks, I didn't even think of that :/
Is this a Golang community recommended approach? Wouldn't there be problems down the line since any other data transformations down the line would always need to check for nil type. It could also slow things down. Ex: You have field1 and field2. You want to create field3 by concatenating field1 and field2. If field2 is nil, cancel.
1

The https://github.com/guregu/null contains null.Int null.String etc. with corresponding JSON serialization/deserialization.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.