Re: [go-nuts] error when unmarshaling EXTRA string=invalid character '\x00' after top-level value

4,898 views
Skip to first unread message

Dave Cheney

unread,
Sep 21, 2012, 9:40:08 AM9/21/12
to Huanchen Zhang, golan...@googlegroups.com
ReadFromUDP can return a packet of any size, from 1 to 2000 bytes, you
need to reslice your buffer using the number of bytes actually read.

json.Unmarshal(buf[:n], &msg)

Also, there is no guarantee that ReadFromUDP will return a complete json blob.

On Fri, Sep 21, 2012 at 5:42 PM, Huanchen Zhang <iamzh...@gmail.com> wrote:
> Hi,
>
> When I try to umarshal a byte array received via udp, and I get the the
> following error %!(EXTRA string=invalid character '\x00' after top-level
> value).
>
> Following are my codes:
>
> buf := make([]byte, 2000)
> n, _, err:= cli.udpConn.ReadFromUDP(buf)
> var msg Message
> json.Unmarshal(buf, &msg)
>
> Anyone has any idea ?
>
> Thank you !
> Huanchen
>
> --
>
>

minux

unread,
Apr 15, 2013, 8:52:27 AM4/15/13
to Reck Hou, golan...@googlegroups.com
On Mon, Apr 15, 2013 at 3:38 PM, Reck Hou <rec...@gmail.com> wrote:
> My code:
> request := make([]byte, 1024)
> read_len, err := conn.Read(request)
> request_right := request[:read_len]
> j := new(Json)
> err := j.UnmarshalJSON(request) // not working
if read_len < len(request) then request will contain extra "\x00" at the end
and that's why UnmarshalJSON(request) won't work.
> err := j.UnmarshalJSON(request_right) // works
>
> but I used fmt.Print(request) & fmt.Print(request_right) and got exactly
> same output, so I think it's a bug of json.UnmarshalJSON or fmt.Print
what does fmt.Print(request) say?

Jan Mercl

unread,
Apr 15, 2013, 8:53:02 AM4/15/13
to Reck Hou, golang-nuts
On Mon, Apr 15, 2013 at 9:38 AM, Reck Hou <rec...@gmail.com> wrote:
> Hi guys, I've met the same issue.
> My code:
> request := make([]byte, 1024)
> read_len, err := conn.Read(request)
> request_right := request[:read_len]
> j := new(Json)
> err := j.UnmarshalJSON(request) // not working
> err := j.UnmarshalJSON(request_right) // works
>
> but I used fmt.Print(request) & fmt.Print(request_right) and got exactly
> same output, so I think it's a bug of json.UnmarshalJSON or fmt.Print

Try instead 'fmt.Printf("% x", request)' and 'fmt.Printf("% x",
request_right)' and compare the outputs.

-j

mingk...@gmail.com

unread,
Sep 16, 2013, 12:55:13 AM9/16/13
to golan...@googlegroups.com
your request is 1024 in length and it seems that UnmarshalJSON considers the blank bytes (which are not filled by conn.Read) in request.
Reply all
Reply to author
Forward
0 new messages