Created
September 28, 2017 14:24
-
-
Save gfldex/c0af5f2033e2cfa5b8570e17712d0d27 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ‚true‘; } | |
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} ], <a b c>.Seq, DateTime, now.DateTime, now; | |
my $repetitions = 64; | |
my @l2 = @l xx $repetitions; | |
say p-to-json(@l2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment