jsonparse: Add basic JSON parser

Some TODO's left and this needs benchmarking.
This commit is contained in:
Yorhel 2025-01-31 07:16:46 +01:00
parent aebe5a93dc
commit 7cdc02e399
8 changed files with 508 additions and 21 deletions

View file

@ -4,8 +4,6 @@ use v5.36;
use FU::XS;
use Exporter 'import';
our @EXPORT_OK = qw/json_format/;
*json_format = *FU::XS::json_format;
our @EXPORT_OK = qw/json_format json_parse/;
1;

View file

@ -20,24 +20,47 @@ functions conform strictly to L<RFC-8259|https://tools.ietf.org/html/rfc8259>,
non-standard extensions are not supported and never will be. It also happens to
be pretty fast, refer to L<FU::Benchmarks> for some numbers.
JSON booleans are decoded into C<builtin::true> and C<builtin::false>. When
JSON booleans are parsed into C<builtin::true> and C<builtin::false>. When
formatting, those builtin constants are the I<only> recognized boolean values -
alternative representations such as C<JSON::PP::true> and C<JSON::PP::false>
are not recognized and attempting to format such values will croak.
JSON numbers that are too large fit into a Perl integer are parsed into a
floating point value instead. This obviously loses precision, but is consistent
with C<JSON.parse()> in JavaScript land - except Perl does support the full
range of a 64bit integer. JSON numbers with a fraction or exponent are also
converted into floating point, which may lose precision as well.
L<Math::BigInt> and L<Math::BigFloat> are not currently supported. Attempting
to format a floating point C<NaN> or C<Inf> results in an error.
=over
=item json_parse($string, %options)
Parse a JSON string and return a Perl value. With the default options, this
function is roughly similar to:
JSON::PP->new->allow_nonref->core_bools-decode($string);
Supported C<%options>:
=over
=item utf8
Boolean, interpret the input C<$string> as a UTF-8 encoded byte string instead
of a Perl Unicode string.
=back
=item json_format($scalar, %options)
Format a Perl value as JSON.
With the default options, this function behaves roughly similar to:
Format a Perl value as JSON. With the default options, this function behaves
roughly similar to:
JSON::PP->new->allow_nonref->core_bools->convert_blessed->encode($scalar);
This function croaks when attempting to format a floating point C<NaN> or
C<Inf>.
Some modules escape the slash character in encoded strings to prevent a
potential XSS vulnerability when embedding JSON inside C<< <script> ..
</script> >> tags. This function does I<not> do that because it might not even