我正在讀取並解碼其中有錯誤的大型JSON響應。現在我需要找到其中的錯誤是!我read about json.SyntaxError但我努力找出如何使用它。從Golang調試JSON錯誤
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"text/template"
"time"
)
type Movie struct {
Title string `json:"title"`
PublishedAt time.Time `json:"published_at"`
}
func main() {
req, _ := http.NewRequest("GET", "https://s.natalian.org/2016-12-07/debugme2.json", nil)
resp, err := http.DefaultClient.Do(req)
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
_, err = dec.Token()
for dec.More() {
var m Movie
if err = dec.Decode(&m); err != nil {
fmt.Println(err)
fmt.Println("Bad", m)
// https://blog.golang.org/error-handling-and-go
if serr, ok := err.(*json.SyntaxError); ok {
fmt.Println("Syntax error", serr)
}
} else {
fmt.Println("Good", m)
}
tmpl := template.Must(template.New("test").Parse("OUTPUT: {{ if .Title }}{{.Title}}{{ if .PublishedAt }} was published at {{.PublishedAt}} {{ end }}{{end}}\n"))
tmpl.Execute(os.Stdout, m)
}
}
我在想什麼?任何工具或策略或建議將不勝感激。我的輸出目前的樣子:
Good {foobar 2016-11-24 16:17:12 +0800 SGT}
OUTPUT: foobar was published at 2016-11-24 16:17:12 +0800 SGT
parsing time ""null"" as ""2006-01-02T15:04:05Z07:00"": cannot parse "null"" as "2006"
Bad {barbar 0001-01-01 00:00:00 +0000 UTC}
OUTPUT: barbar was published at 0001-01-01 00:00:00 +0000 UTC
Good { 1999-12-24 16:11:12 +0200 +0200}
OUTPUT:
Good {Something else entirely 2000-01-24 16:11:12 +0200 +0200}
OUTPUT: Something else entirely was published at 2000-01-24 16:11:12 +0200 +0200
但我需要這樣的事情在我的錯誤輸出到更好的調試問題:
Line 8: published_at is invalid
等的標題也許有些情況下,所以我可以告訴API後端團隊在他們的JSON響應中出現錯誤。
獎金問題:而且我不希望打印的價值0001-01-01 00:00:00 +0000 UTC因爲它居然真的空。我並不介意它錯過了。
錯誤消息確切地告訴錯誤在哪裏。 *解析時間「」null「」as「」2006-01-02T15:04:05Z07:00「」:無法解析「null」爲「2006」*。在您的JSON正文中,您已將null鍵入爲字符串(「null」)。嘗試刪除引號。 – Nadh
我知道有一個錯誤,因爲我把它放在那裏。我的問題是問如何打印錯誤發生的地方。 – hendry
你試過'json.unmarshal() '函數?如果有任何可以幫助你的函數,它會返回錯誤,請參見[https://play.golang.org/p/eQCG-RE5sK](https://play.golang.org/p/eQCG-RE5sK ) – tgogos