[dancer-users] Returning JSON Data
Richard Jones
ra.jones at dpw.clara.co.uk
Sun Sep 13 18:29:31 BST 2015
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
More information about the dancer-users
mailing list