views:

619

answers:

4

e.g. (Mason code):

 16 %   # convert our @cti data structure into a javascript one
 17     var cti = [
 18 % foreach my $cti_category (@cti) {
 19                 {
 20                       label: "<% $cti_category->{'label'} %>",
 21                       value: "<% $cti_category->{'value'} %>",
 22                    children:  [
 23 %     foreach my $cti_type (@{$cti_category->{'children'}}) {
 24                                 {
 25                                   label: "<% $cti_type->{'label'} %>",
 26                                   value: "<% $cti_type->{'value'} %>",
 27                                 },
 28 %     }
 29                               ]
 30                 },
 31 % }
 32               ];
+7  A: 

Check out JSON or JSON::XS.

To elaborate a bit more, JSON is "JavaScript Object Notation", and the two modules above convert perl data structures into that format.

moritz
A: 

JSON!

Dan
A: 

The JSON module will convert data structures - it's basically a to/from JSON serializer.

Kyle Burton
+14  A: 

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.

Penfold