[dancer-users] Returning JSON Data
Kadir Beyazlı
kadirbeyazli at gmail.com
Sun Sep 13 18:07:42 BST 2015
Hi All,
I understood my mistake, last line of my code was:
return $branch_list;
but it should be
return @\$branch_list;
But I have one more problem, how I can I set character set of JSON data to utf8?
I was doing it as follow as I wrote at my 1st mail
print $q->header(-content_type => "application/json; charset='utf8');
Now, how I will do it?
Also why am I unable to use :
use JSON
which is general way?
On Sun, Sep 13, 2015 at 7:54 PM, Kadir Beyazlı <kadirbeyazli at gmail.com> wrote:
> Hi All,
>
> I will return JSON data from a route.
> If I don't use Dancer2 framework, I do it as follow and it works:
>
> sub json_branch_list {
>
> my $sth_branch = $dbh->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}
> };
> }
>
> use JSON;
>
> my $result = { total => scalar(@$branch_list),
> branch => $branch_list,
> success => JSON::true
> };
>
> print $q->header(-content_type => "application/json; charset='utf8');
>
> print to_json($result);
>
> exit;
> }
>
> 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
>
> --
> Kadir Beyazlı
> Computer Engineer
> GSM : +90 535 821 50 00
--
Kadir Beyazlı
Computer Engineer
GSM : +90 535 821 50 00
More information about the dancer-users
mailing list