Permalink
Browse files

work around absence of Str.trans. Does not work yet, since char class…

…es with ranges in them seem to be busted
  • Loading branch information...
1 parent 2b5fc58 commit 0b4e5ca9836ca6bf3010340ce12137587b5f32e8 @moritz committed Nov 20, 2011
Showing with 20 additions and 5 deletions.
  1. +20 −5 lib/JSON/Tiny.pm
View
@@ -23,12 +23,27 @@ proto to-json($) is export {*}
multi to-json(Real:D $d) { ~$d }
multi to-json(Bool:D $d) { $d ?? 'true' !! 'false'; }
multi to-json(Str:D $d) {
+# RAKUDO/nom doesn't do .trans yet
+# '"'
+# ~ (~$d).trans(['"', '\\', "\b", "\f", "\n", "\r", "\t"]
+# => ['\"', '\\\\', '\b', '\f', '\n', '\r', '\t'])\
+# # RAKUDO: This would be nicer to write as <-[\c32..\c126]>,
+# # but Rakudo doesn't do \c yet. [perl #73698]
+# .subst(/<-[\ ..~]>/, { ord(~$_).fmt('\u%04x') }, :g)
+# ~ '"'
+ state %esc =
+ '"' => '\"',
+ '\\' => '\\\\',
+ '\b' => '\b',
+ '\f' => '\f',
+ '\n' => '\n',
+ '\r' => '\r',
+ '\t' => '\t',
+ ;
+
'"'
- ~ (~$d).trans(['"', '\\', "\b", "\f", "\n", "\r", "\t"]
- => ['\"', '\\\\', '\b', '\f', '\n', '\r', '\t'])\
- # RAKUDO: This would be nicer to write as <-[\c32..\c126]>,
- # but Rakudo doesn't do \c yet. [perl #73698]
- .subst(/<-[\ ..~]>/, { ord(~$_).fmt('\u%04x') }, :g)
+ ~ (~$d).subst(/<["\\\b\f\n\r\t]>/, { %esc{$_} }, :g)\
+ .subst(/<-[# ..~]-[\ ]>/, { ord(~$_).fmt('\u%04x') }, :g)
~ '"'
}
multi to-json(Array:D $d) {

0 comments on commit 0b4e5ca

Please sign in to comment.