Re: Struggling with Perl data structure for JSON object

[email protected] (Niels Jakob Darger) Sat, 10 Dec 2011 18:11:04 +0100
Newsgroups perl.copenhagen
Message-ID <[email protected]>
I would use the excellent JSON::XS module. There is also the pure Perl 
JSON::PP module (I've never used it but I would imagine it's a slower 
drop-in replacement for JSON::XS). Alternatively you can use the JSON 
module which loads whatever is on the system, preferring JSON::XS.

use JSON::XS;
[...]
print encode_json($data->[0]{servers});

I wouldn't generate JSON myself, you'll eventually end up generating a 
document which is not well-formed if there's any character (set) 
surprises etc. The JSON modules handle everything - escaping, UTF-8 etc.

Hilsen / regards,
Niels Jakob Darger


On 2011-12-10 17:22, Thomas Elsgaard wrote:
> Hi CPH.pm
>
> I am struggling a little with storing a mysql result set into a JSON object.
>
> Which requires a data structure like this:
>
>   my $data = [
>      {
>        'servers' =>  [
>                       {
>                         'DateTime' =>  '2011-11-13 13:04:00',
>                         'TotalNumberOfUsersRegistered' =>  '1205.00'
>                       },
>                       {
>                         'DateTime' =>  '2011-11-13 13:00:00',
>                         'TotalNumberOfUsersRegistered' =>  '1205.00'
>                       }
>                     ]
>      }
>   ];
>
>
> Any good suggestions for how i can get the result set from my data
> fetch routine below, into a data structure like the one above, in a
> "pretty way" ?
>
>
> #####################
>
> while(my $ref = $sth->fetchrow_hashref()) {
>   print "DateTime: $ref->{'DateTime'}\n";
>   print "TotalNumberOfUsersRegistered: $ref->{'TotalNumberOfUsersRegistered'}\n";
>   }
>
> #####################
>
>
> The end result should be a JSON object like this:
>
> [{"TotalNumberOfUsersRegistered":"1205.00","DateTime":"2011-11-13
> 13:04:00"},{"TotalNumberOfUsersRegistered":"1205.00","DateTime":"2011-11-13
> 13:00:00"}]
>
> Best regards
>
> ///Thomas