meltdown90 meltdown90 - 7 months ago 13
Perl Question

Perl Dancer - JSON serializer and JSON arrays

I have a problem working with the built in Perl Dancer serializer for JSON and JSON arrays.

I activated the serializer in the app.pl file:

#!/usr/bin/env perl
use Dancer;
use main;

set serializer => 'JSON';

dance;


In the module itself I tested the JSON parsing like this:

post '/test/' => sub {
my $params = request->params;

debug('Test: ', $params);
};


Now I wanted to make sure the JSON gets parsed as expected, so I tried using cURL to understand the way the serializer works:

curl -H "Content-Type: application/json" -X POST http://localhost:3000/test/ -d '{ "Name" : "foo", "email" : "bar" }'


The result was as expected:

Test: {'Name' => 'foo','email' => 'bar'}


But trying to send an array:

curl -H "Content-Type: application/json" -X POST http://localhost:3000/test/ -d '[{ "Name" : "foo", "email" : "bar" }]'


Resulted in:

Test: {}


I expected the serializer to return an array reference, but it seems like it returns an empty hash. I tried using the serializer the other way around, but encoding JSONs seems to work as expected. What have I done wrong?

Answer

Thought I had code that did this but, was mistaken.

I couldn't get params to parse anything with any depth. Maybe that's by design but, not really clear to me from the documentation.

Using the from_json function directly you can parse request->body which contains the POST'd JSON string:

Note: I use'd Data::Dumper to print variable contents to try to make it a little clearer.

post '/test/' => sub {
 #my @params =   params  ;
 #my @params =   request->body;
 my $body = request->body;

 my $j_O = from_json( $body );

 #deubg( 'Test1: ' . Dumper( request->body ) );
 #debug( 'Test2: ' . Dumper( request->params ) );
 #debug( 'Test3: ' . Dumper( { params }  ) );
 debug( 'Test4: ' . Dumper( $body ) );
 debug( 'Test5: ' . Dumper( $j_O ) );


};

OUTPUT:

[27993] debug @0.001528> [hit #2]Test4: $VAR1 = '[ { "Name" : "foo", "email" : "bar" }, { "Name" : "bar"} ]'; in /media/truecrypt1/Projects/Perl5+/Dancer/Test/lib/Test.pm l. 23
[27993] debug @0.001772> [hit #2]Test5: $VAR1 = [
          {
            'email' => 'bar',
            'Name' => 'foo'
          },
          {
            'Name' => 'bar'
          }
        ];