Last active
October 22, 2015 17:40
-
-
Save mattn/6550bc27cf55f11d1136 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; | |
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