Skip to content

Instantly share code, notes, and snippets.

@mweibel
Created May 29, 2017 15:39
Show Gist options
  • Save mweibel/97e93f09e543961aa14f0fc3697fedb0 to your computer and use it in GitHub Desktop.
Save mweibel/97e93f09e543961aa14f0fc3697fedb0 to your computer and use it in GitHub Desktop.
json.Unmarshal vs. json.NewDecoder

Go json unmarshal vs using the decoder

When running main_unmarshal.go:

$ go run ./main_unmarshal.go
Input 2:
json syntax error: unexpected end of JSON input at offset 144

When running main_decoder.go:

$ go run ./main_decoder.go
Input 2:
json default: unexpected EOF%

Why?

[
{
"id": "d421e09c-3479-11e7-90b6-7831c1ca8e1e",
"created_at": "2017-05-09T10:00:00Z",
"numbers": [
12,
43,
54
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"time"
)
type link struct {
Href string `json:"href"`
}
type links struct {
Self link `json:"self"`
Parent link `json:"parent"`
}
type numberItem struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
Numbers []int `json:"numbers"`
Links links
}
func readFile(filename string) {
f, err := os.Open(filename)
if err != nil {
fmt.Printf("readFile: %s", err)
os.Exit(0)
}
ni := make([]numberItem, 0)
err = json.NewDecoder(f).Decode(&ni)
if err != nil {
switch err := err.(type) {
case *json.SyntaxError:
fmt.Printf("json syntax error: %s at offset %d\n", err, err.Offset)
default:
fmt.Printf("json default: %s", err)
}
os.Exit(0)
}
}
func main() {
fmt.Println("Input 2:")
readFile(filepath.Join(".", "input2.json"))
}
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
)
type link struct {
Href string `json:"href"`
}
type links struct {
Self link `json:"self"`
Parent link `json:"parent"`
}
type numberItem struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
Numbers []int `json:"numbers"`
Links links
}
func readFile(filename string) {
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Printf("readFile: %s", err)
os.Exit(0)
}
ni := make([]numberItem, 0)
err = json.Unmarshal(data, &ni)
if err != nil {
switch err := err.(type) {
case *json.SyntaxError:
fmt.Printf("json syntax error: %s at offset %d\n", err, err.Offset)
default:
fmt.Printf("json default: %s", err)
}
os.Exit(0)
}
}
func main() {
fmt.Println("Input 2:")
readFile(filepath.Join(".", "input2.json"))
}
@mweibel
Copy link
Author

mweibel commented May 29, 2017

Got a nice reply from @ivanjovanovic:

https://twitter.com/ivanjovanovic/status/869217714153324544

First takes file handle and expects to read more from it. Second takes data and says it has invalid syntax.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment