Skip to content

Instantly share code, notes, and snippets.

@mattn
Last active October 22, 2015 17:40
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 mattn/6550bc27cf55f11d1136 to your computer and use it in GitHub Desktop.
Save mattn/6550bc27cf55f11d1136 to your computer and use it in GitHub Desktop.
use v6;
use Test;
sub to-json($arg) {
given $arg.^name {
when 'Bool' { $arg.Str.lc }
when 'Int' { $arg.Str }
when 'Rat' { $arg.Str }
when 'Num' { $arg.Str }
when 'Str' { $arg.Str.perl }
when 'Array' { "[{{$arg.map(&to-json).join(',')}}]" }
when 'Hash' { "\{{{$arg.map(&to-json).join(',')}}\}" }
when 'Pair' { "{{to-json $arg.key}}:{{to-json $arg.value}}" }
default { die "WHY JAPANESE PEOPLE!: {{$arg.^name}}" }
}
}
Any.^add_method('to-json', method () { to-json self; });
.^compose for [Num,Int,Rat,Array,Str,Hash,Bool];
is [1, "foo"].to-json, '[1,"foo"]';
is 1.to-json, '1';
is 1.2.to-json, '1.2';
is True.to-json, 'true';
is False.to-json, 'false';
is { foo => "bar", {bar => 'baz'}}.to-json, '{"bar":"baz","foo":"bar"}';
is 1e9.to-json, 1000000000;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment