Skip to content

Instantly share code, notes, and snippets.

@gfldex
Last active October 17, 2017 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gfldex/b9914d412c807f45d2d041d45726f2b2 to your computer and use it in GitHub Desktop.
Save gfldex/b9914d412c807f45d2d041d45726f2b2 to your computer and use it in GitHub Desktop.
use v6.d.PREVIEW;
use Test;
sub p-to-json($_ is raw) {
# note .^name;
sub str-escape($text) {
return $text unless $text ~~ /<[\x[5C] \x[22] \x[00]..\x[1F]]>/;
$text.subst(/(<[\x[5C] \x[22] \x[00]..\x[1F]]>)/, {'\u' ~ $0.ord.fmt('%04x')}, :g);
}
when Bool { return .item ?? ‚true‘ !! ‚false‘; }
when !.defined { return ‚null‘; }
when Int|Rat {return .Str; }
when Num {
when NaN | -Inf | Inf {
return ‚null‘;
}
default { return .Str }
}
when Str { return „"{str-escape .Str}"“ }
when Dateish { return „"{.Str}"“ }
when Instant { return „"{.DateTime.Str}"“ }
when Seq {
return ‚[‘ ~ .cache.hyper.map(*.&p-to-json).join(',') ~ ‚]‘;
}
when Positional {
return ‚[‘ ~ .hyper.map(*.&p-to-json).join(',') ~ ‚]‘;
}
when Associative {
return ‚{‘ ~
.pairs.hyper.map(-> Pair (:$key, :$value) { „"$key":{$value.&p-to-json}“}).join(',')
~ ‚}‘;
}
default {
„"{str-escape .Str}"“;
}
}
my @l = 1, ½, (1/3).Num, ∞, :1a, [:2b, c => {:4e, :5f} ], ( 1, (2, |(<a b c> xx 10) ) ), <a b c>.Seq, DateTime, now.DateTime, now;
my $repetitions = 100;
my @l2 = |@l xx $repetitions;
{
my $s = p-to-json(@l2);
print now - (ENTER now) ~ 's ';
print $s.chars ~ ' ';
}
# while true; do perl6 to-json-parallel.p6; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment