go icon indicating copy to clipboard operation
go copied to clipboard

Valid() function returns true with string started with number which should be false

Open M-AIDEZ opened this issue 5 years ago • 2 comments

For example:

func TestSomething(t *testing.T) {
	valid := jsoniter.Valid([]byte("abc"))
	require.False(t, valid)
}

returns false and pass the test case, but

func TestSomething(t *testing.T) {
	valid := jsoniter.Valid([]byte("123abc"))
	require.False(t, valid)
}

returns true which shoud be false.

M-AIDEZ avatar Dec 14 '20 08:12 M-AIDEZ

It seems Valid() only skip one json object without checking whether there would be any data left Here is one workaround:

func ValidJson(data []byte) bool {
	iter := jsoniter.ConfigDefault.BorrowIterator(data)
	defer jsoniter.ConfigDefault.ReturnIterator(iter)
	iter.Skip()
	if iter.Error != nil {
		return false
	}
	iter.WhatIsNext()           //  read non-empty character
	return iter.Error == io.EOF // io.EOF means there is no more data to be parsed 
}

JeckieLI avatar Dec 14 '20 08:12 JeckieLI

One more adjustment to add to @JeckieLI's workaround. Skipping number at the end of the file sets iter.Error to io.EOF. A workaround for that is data = append(data, '\n') at the beginning of the func.

WillAbides avatar Mar 28 '21 23:03 WillAbides