Skip to content

Instantly share code, notes, and snippets.

@gfldex
Created September 28, 2017 14:24
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/c0af5f2033e2cfa5b8570e17712d0d27 to your computer and use it in GitHub Desktop.
Save gfldex/c0af5f2033e2cfa5b8570e17712d0d27 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 ‚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