Skip to content

Instantly share code, notes, and snippets.

@mattn
Created October 22, 2015 17:26
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/4ca8fbe17aa895041a42 to your computer and use it in GitHub Desktop.
Save mattn/4ca8fbe17aa895041a42 to your computer and use it in GitHub Desktop.
sub to-json($arg) {
given $arg.^name {
when 'Bool' { $arg.Str.lc }
when 'Int' { $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; });
Int.^compose;
Array.^compose;
Str.^compose;
Hash.^compose;
Bool.^compose;
say [1, "foo"].to-json;
say 1.to-json;
say True.to-json;
say { foo => "bar", bar => 'baz' }.to-json;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment