mojolicious / mojo

:sparkles: Mojolicious - Perl real-time web framework
https://mojolicious.org
Artistic License 2.0
2.67k stars 580 forks source link

possible Mojo::JSON::decode_json bug #1476

Closed pavelsr closed 4 years ago

pavelsr commented 4 years ago

Steps to reproduce the behavior

$ cat test.pl 
use Mojo::JSON 'decode_json';
warn decode_json(undef);
$ perl test.pl 
malformed JSON string, neither tag, array, object, number, string or atom, at character offset 0 (before "(end of string)") at /usr/local/share/perl5/site_perl/Mojo/JSON.pm line 39

Expected behavior

I think decode_json must return undef

Actual behavior

decode_json dies

pavelsr commented 4 years ago

Same problem if decode_json('')

haarg commented 4 years ago

The current behavior seems correct to me.

pink-mist commented 4 years ago

Mojo::JSON implements RFC-8259 in which you can see the JSON Grammar being defined as follows:

    JSON-text = ws value ws
    [...]
    ws = *(
              %x20 /              ; Space
              %x09 /              ; Horizontal tab
              %x0A /              ; Line feed or New line
              %x0D )              ; Carriage return
    [...]
    value = false / null / true / object / array / number / string
    [...]
    false = %x66.61.6c.73.65   ; false
    null  = %x6e.75.6c.6c      ; null
    [...]
    string = quotation-mark *char quotation-mark

This means that an empty string is not valid JSON, it needs at the very least some quotation marks inside

Grinnz commented 4 years ago

If you think you might have an empty value instead of valid JSON, you can easily check length $json before attempting to decode.

karenetheridge commented 4 years ago

If it's a bug, it would be with the backend that is being used (Cpanel::JSON::XS in most cases, unless you twiddled some environment variables -- see the Mojo::JSON source, as it's not long).