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")) | |
} |
Got a nice reply from @ivanjovanovic:
https://twitter.com/ivanjovanovic/status/869217714153324544