json-parse-better-errors icon indicating copy to clipboard operation
json-parse-better-errors copied to clipboard

Better error for empty string

Open rdmurphy opened this issue 7 years ago • 2 comments

Hello! 👋

Have been on the hunt for better ways to return feedback with JSON.parse, and was thrilled to find this. Recently I hit a new-to-me error with JSON.parse — you cannot do a parse against an empty string. It'll throw the following:

Uncaught SyntaxError: Unexpected end of JSON input

With json-parse-better-errors it is better, but still a little cryptic:

SyntaxError: Unexpected end of JSON input while parsing near ''

Neither gives much feedback in terms of "hey, you just tried to pass me nothing." Much like the catch for the passing of a non-string or Array, do you think something like this would be within the scope of json-parse-better-errors?

I'm not 100% sure what would be the best way to determine when something is truly an empty string, though. Maybe a combination of String.prototype.trim() and a string.length check?

Thanks for the useful library!

rdmurphy avatar Jun 13 '18 14:06 rdmurphy

@rdmurphy I agree that it is a bit confusing message to see.

For me, it seems that it is confusing because it says "near" while it shows the whole string you passed. If the message was, for example

Unexpected end of JSON input while parsing near '...aaaaaaaaaaaaaaaaaaaaa'

it makes sense. (For you too, I hope)

I think the appropriate improvement would be omitting the word "near" if it shows the whole string you tried to parse, so that it would say

Unexpected end of JSON input while parsing ''
Unexpected end of JSON input while parsing '      '

This covers more cases than just special-casing empty-ish strings.

Hoishin avatar Aug 26 '18 03:08 Hoishin

Hi, i am trying to run npm audit for my project where i am receiving an error message saying npm ERR! Unexpected end of JSON input while parsing near ' ' .Any suggestions or fixes for this issue would be greatly appreciated!!Thanks

shiv0808 avatar Feb 17 '22 14:02 shiv0808