[dancer-users] Returning JSON Data

Kadir Beyazlı kadirbeyazli at gmail.com
Sun Sep 13 18:43:51 BST 2015


Hi John,

Now it is OK me.  I am using as follow

  while (my $branch = $sth_branch->fetchrow_hashref) {

    push @$branch_list,
      { BranchID => $branch->{BranchID},
    Branch   => 'ali'
      };
  }

  my $result = { total   => scalar(@$branch_list),
                 branch  => $branch_list,
                 success => 'true'
           };

  set serializer => 'JSON';
  return $result;

If I use

set serializer => 'JSON';

I dont need to use to_json as I understand. This is good for me

I also understood why I dont need to define

use JSON

Because it is already ready for me.

Thanks



On Sun, Sep 13, 2015 at 8:29 PM, Richard Jones <ra.jones at dpw.clara.co.uk> wrote:
> On 13/09/2015 17:54, Kadir Beyazlı wrote:
>>
>> At Dancer2, when I write below definition :
>>
>> use JSON;
>>
>> it does not allow with a warning that to_json and from_json functions
>> are duplicated. I of course know that Dancer2 is using following
>> definition
>>
>> set serializer => 'JSON';
>>
>> But I still could not achieve returnin JSON data: Here my route is
>>
>> get '/json_branch_list' => sub {
>>
>>    my $sth_branch = database->prepare
>>      (qq(SELECT BranchID,Branch
>>          FROM branch
>>          WHERE Deleted=0
>>         ));
>>
>>    $sth_branch->execute || die 'SQL_ERROR';
>>
>>    my $branch_list = [];
>>
>>    while (my $branch = $sth_branch->fetchrow_hashref) {
>>
>>      push @$branch_list,
>>        { BranchID => $branch->{BranchID},
>>      Branch   => $branch->{Branch}
>>        };
>>    }
>>
>>    set serializer => 'JSON';
>>
>>     return $branch_list;
>> };
>>
>> No data is displayed
>>
>
> What happens if you do:
>
> get '/json_branch_list' => sub {
>   [...]
>   my $ref = {
>     BranchID => $branch->{BranchID},
>     Branch   => $branch->{Branch}
>   };
>   return to_json($ref);
> }
>
> Or even, depending on what is in $branch and what you want to do with it
> downstream just return the hashref as-is:
>   return to_json($branch);
>
> As far I as I know there is no need for 'use JSON', just 'use Dancer2'.
> Works for me anyway.
>
>
> --
> Richard Jones
>
> _______________________________________________
> dancer-users mailing list
> dancer-users at dancer.pm
> http://lists.preshweb.co.uk/mailman/listinfo/dancer-users



-- 
Kadir Beyazlı
Computer Engineer
GSM : +90 535 821 50 00


More information about the dancer-users mailing list