Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I find a Perl module for converting a Perl data structure into a JavaScript one?

Where can I find a Perl module for converting a Perl data structure into a JavaScript one?

e.g. this is my code (Mason):

% # convert our @cti data structure into a javascript one
  var cti = [
% foreach my $cti_category (@cti) {
             {
                 label: "<% $cti_category->{'label'} %>",
                 value: "<% $cti_category->{'value'} %>",
                 children: [
%     foreach my $cti_type (@{$cti_category->{'children'}}) {
                            {
                              label: "<% $cti_type->{'label'} %>",
                              value: "<% $cti_type->{'value'} %>",
                            },
%     }
                           ]
             },
% }
            ];

is there a module for this?

like image 468
someguy Avatar asked Nov 29 '22 07:11

someguy


1 Answers

JSON stands for JavaScript Object Notation, which is the format you're looking for.

Unfortunately, none of the modules you're looking for are in the Perl core, but they are available on CPAN, as a quick search will reveal.

I'd actually recommend installing JSON::Any as a wrapper, as well as JSON::XS (if you have a C compiler) or one of JSON and JSON::Syck if you don't. JSON::Any provides an interface class on top of several other JSON modules (you can choose, or let it pick from what's installed) that's independent of which module you wind up using. That way, if your code should need to be ported elsewhere, and (say) the target machine can install JSON::XS when you can't, you get a performance boost without any extra code.

use JSON::Any;

my $j = JSON::Any->new;

$json = $j->objToJson($perl_data);

Like so.

like image 92
Penfold Avatar answered Dec 05 '22 10:12

Penfold