Panic when unmarshaling JSON


(yofri) #1

Error: panic: invalid character '\x00' after top-level value

Code:

	f, e := os.OpenFile(pathFile, os.O_RDWR, 0644)
	checkErr(e)
	defer f.Close()

    b := make([]byte, 1024)
	for {
		ln, e := f.Read(b)
		if e != io.EOF {
			checkErr(e)
		}
		if ln == 0 {
			break
		}
	}
    fmt.Println(string(b)) // [{"key":"v a l u e"}] json shown here

	var d []struct{
        Title string
        Body string
    }
	e = json.Unmarshal(b, &d)
	checkErr(e) // error thrown here

(yofri) #2

So I just know that the byte will append \x00 to the left over byte slice size.

The solution is to trim it with bytes.Trim()