Mose
Mose

Reputation: 563

Perl JSON module | unable to get a JSON response

I have a script that I am using to populate a JQgrid object.The following code that when executed from the CLI builds what appears to be a valid JSON query

#!/usr/bin/perl 
use CGI;
use DBI;
use JSON;
use Test::JSON;
use POSIX qw(ceil);
use strict;
use warnings;

my $cgi = CGI->new;
my $page = $cgi->param('page');
my $limit = $cgi->param('limit');
my $sidx = $cgi->param('sidx');
my $sordx = $cgi->param('sordx');

if(!$sidx) {$sidx = 1};
my $start = $limit*$page - $limit;

my $dbh = DBI->connect('dbi:mysql:hostname=localhost;database=test',"test","test") or die $DBI::errstr;
my $count = $dbh->selectrow_array("SELECT COUNT(id) AS count FROM test;");
my $sql = "SELECT ID, Name FROM test ORDER BY ? ? LIMIT ?, ?;";
my $sth = $dbh->prepare($sql) or die $dbh->errstr;

$sth->execute($sidx,$sordx,$start,$limit) or die $sth->errstr;
my $total_pages;
if( $count >0 ) {
        $total_pages = ceil($count/$limit);
} else {
        $total_pages = 0;
}
if ($page > $total_pages){ $page=$total_pages};
$start = $limit*$page - $limit;
my $i=0;
my $response = {};
$response->{page} = $page;
$response->{total} = $total_pages;
$response->{records} = $count;
        while (my $row = $sth->fetchrow_arrayref) {
                my @arr = @{$row};
                $response->{rows}[$i]{id} = $row->[0];
                $response->{rows}[$i]{cell} = \@arr;
                $i++;
        }

Test::JSON::is_valid_json $response, '... json is well formed';

print $cgi->header(-type => "application/json", -charset => "utf-8");
print JSON::to_json($response,{ ascii => 1, pretty => 1 });

If I put the script into CGI debug mode, it returns the following (Note, manually edited to mask sensitive data):

{
   "page" : "1",
   "records" : "35",
   "rows" : [
      {
         "id" : "15675",
         "cell" : [
            "15675",
            "Test 1"
         ]
      },
      {
         "id" : "15676",
         "cell" : [
            "15676",
            "Test 2"
         ]
      }
   ],
   "total" : 4
}

Edit: I added Test::JSON package, and it gives me the following error:

input was not valid JSON: malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)") at /usr/lib/perl5/site_perl/5.8.8/JSON/Any.pm line 571.

I'm not sure where to go next with this. Any other changes I make to the code will not put the appropriate brackets in place on the returned string.

Upvotes: 3

Views: 4212

Answers (1)

mob
mob

Reputation: 118605

Passing this string into JSON::decode, I see complaints about the literal newlines in the strings "This is record 1" and "This is record 2". What if you convert them to \n?

foreach my $row ( @{$ref} ) {
    $response->{rows}[$i]{id} = @$row[0];
    $response->{rows}[$i]{cell} = $row;

    # escape newlines in database output
    s/\n/\\n/g for @{$response->{rows}[$i]{cell}};

    $i++;
}

(There's probably a more general and more robust way to do this)

Upvotes: 1

Related Questions