title: Perl JSON module | unable to get a JSON response
body: <p>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</p>
  
  <pre><code>#!/usr/bin/perl 
  use CGI;
  use DBI;
  use JSON;
  use Test::JSON;
  use POSIX qw(ceil);
  use strict;
  use warnings;
  
  my $cgi = CGI-&gt;new;
  my $page = $cgi-&gt;param('page');
  my $limit = $cgi-&gt;param('limit');
  my $sidx = $cgi-&gt;param('sidx');
  my $sordx = $cgi-&gt;param('sordx');
  
  if(!$sidx) {$sidx = 1};
  my $start = $limit*$page - $limit;
  
  my $dbh = DBI-&gt;connect('dbi:mysql:hostname=localhost;database=test',"test","test") or die $DBI::errstr;
  my $count = $dbh-&gt;selectrow_array("SELECT COUNT(id) AS count FROM test;");
  my $sql = "SELECT ID, Name FROM test ORDER BY ? ? LIMIT ?, ?;";
  my $sth = $dbh-&gt;prepare($sql) or die $dbh-&gt;errstr;
  
  $sth-&gt;execute($sidx,$sordx,$start,$limit) or die $sth-&gt;errstr;
  my $total_pages;
  if( $count &gt;0 ) {
          $total_pages = ceil($count/$limit);
  } else {
          $total_pages = 0;
  }
  if ($page &gt; $total_pages){ $page=$total_pages};
  $start = $limit*$page - $limit;
  my $i=0;
  my $response = {};
  $response-&gt;{page} = $page;
  $response-&gt;{total} = $total_pages;
  $response-&gt;{records} = $count;
          while (my $row = $sth-&gt;fetchrow_arrayref) {
                  my @arr = @{$row};
                  $response-&gt;{rows}[$i]{id} = $row-&gt;[0];
                  $response-&gt;{rows}[$i]{cell} = \@arr;
                  $i++;
          }
  
  Test::JSON::is_valid_json $response, '... json is well formed';
  
  print $cgi-&gt;header(-type =&gt; "application/json", -charset =&gt; "utf-8");
  print JSON::to_json($response,{ ascii =&gt; 1, pretty =&gt; 1 });
  </code></pre>
  
  <p>If I put the script into CGI debug mode, it returns the following (Note, manually edited to mask sensitive data):</p>
  
  <pre><code>{
     "page" : "1",
     "records" : "35",
     "rows" : [
        {
           "id" : "15675",
           "cell" : [
              "15675",
              "Test 1"
           ]
        },
        {
           "id" : "15676",
           "cell" : [
              "15676",
              "Test 2"
           ]
        }
     ],
     "total" : 4
  }
  </code></pre>
  
  <p>Edit: I added Test::JSON package, and it gives me the following error:</p>
  
  <blockquote>
    <p>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.</p>
  </blockquote>
  
  <p>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.</p>