Moritz Lenz > JSON-Tiny-0.1.2_1 > lib/JSON/Tiny.pm

Download:
JSON-Tiny-0.1.2_1.tar.gz

Annotate this POD

CPAN RT

Open  0
View/Report Bugs
Source  

module JSON::Tiny { use JSON::Tiny::Actions; use JSON::Tiny::Grammar;

    sub from-json($text) is export {
        my $a = JSON::Tiny::Actions.new();
        my $o = JSON::Tiny::Grammar.parse($text, :action($a));
        return $o.ast;
    }

    multi to-json(Num $d) is export { $d }
    multi to-json(Int $d) { $d }
    multi to-json(Str $d) { 
        # RAKUDO BUG #66596 (can't .subst in multis)
        string-to-json($d);
    }
    multi to-json(Array $data) {
        return  '[ ' 
               ~ (map { to-json($_) }, $data.values).join(', ')
               ~ ' ]';
    }
    multi to-json(Hash  $data) {
        return '{ '
               ~ (map { to-json(.key) ~ ' : ' ~ to-json(.value) }, $data.pairs).join(', ')
               ~ ' }';
    }
    multi to-json(Bool  $data) { $data ?? 'true' !! 'false'; }
    multi to-json($s) { die }

    # RAKUDO BUG #66596 (can't .subst in multis)
    sub string-to-json($d) {
        '"'
        ~ $d.trans(['"',  '\\',   "\b", "\f", "\n", "\r", "\t"]
                => ['\"', '\\\\', '\b', '\f', '\n', '\r', '\t'])\
             .subst(/<-[\c0..\c127]>/, { sprintf '\u%04x', ord(~$_) }, :g)
        ~ '"'
    }
}
# vim: ft=perl6
syntax highlighting: