Put integers in quotes as well. Proper JSON has all values in quotes. This is important because integers like 0123 are invalid

This commit is contained in:
Isaac Connor 2022-02-26 11:56:29 -05:00
parent 6fc5803e16
commit 2bd85089f4
1 changed files with 20 additions and 19 deletions

View File

@ -432,13 +432,13 @@ our $testedJSON = 0;
our $hasJSONAny = 0;
sub _testJSON {
return if ( $testedJSON );
return if $testedJSON;
my $result = eval {
require JSON::MaybeXS;
JSON::MaybeXS->import();
};
$testedJSON = 1;
$hasJSONAny = 1 if ( $result );
$hasJSONAny = 1 if $result;
}
sub _getJSONType {
@ -451,40 +451,41 @@ sub _getJSONType {
return 'string';
}
sub jsonEncode;
sub jsonEncode {
my $value = shift;
_testJSON();
if ($hasJSONAny) {
my $string = eval { JSON::MaybeXS->encode_json( $value ) };
Fatal( "Unable to encode object to JSON: $@" ) unless( $string );
return( $string );
my $string = eval {
JSON::MaybeXS->encode_json($value);
};
Error('Unable to encode object to JSON: '.$@) unless $string;
return $string;
}
my $type = _getJSONType($value);
if ($type eq 'integer' || $type eq 'double') {
return( $value );
return '"'.$value.'"';
} elsif ($type eq 'boolean') {
return( $value?'true':'false' );
return $value ? 'true' : 'false';
} elsif ( $type eq 'string' ) {
$value =~ s|(["\\/])|\\$1|g;
$value =~ s|\r?\n|\n|g;
return( '"'.$value.'"' );
return '"'.$value.'"';
} elsif ( $type eq 'null' ) {
return( 'null' );
return 'null';
} elsif ( $type eq 'array' ) {
return( '['.join( ',', map { jsonEncode( $_ ) } @$value ).']' );
return '['.join( ',', map { jsonEncode( $_ ) } @$value ).']';
} elsif ( $type eq 'hash' ) {
my $result = '{';
while ( my ( $subKey=>$subValue ) = each(%$value) ) {
$result .= ',' if ( $result ne '{' );
$result .= '"'.$subKey.'":'.jsonEncode($subValue);
}
return( $result.'}' );
return $result.'}';
} else {
Fatal( "Unexpected type '$type'" );
Error("Unexpected type '$type'");
return '';
}
}