chinna_82
chinna_82

Reputation: 6403

Perl string to Json

package Emp;
sub new
{
    my $class = shift;
    my $self = {
        OrderID => shift,
        OrderDate  => shift,
        CustomerID  => shift,
        ShipName  => shift,
        Freight  => shift,
    };
    bless $self, $class;
    return $self;
}
sub TO_JSON { return { %{ shift() } }; }

package main;
use JSON;

my $JSON  = JSON->new->utf8;
$JSON->convert_blessed(1);

$e = new Emp( "10248", "1996-07-04", "WILMK","Vins","10");
$json = $JSON->encode($e);
print "$json\n";    

I try to convert my String to JSON by using above example. The output is like below:

{"Freight":"10","OrderDate":"1996-07-04","CustomerID":"WILMK","OrderID":"10248","ShipName":"Vins"}

Where do I change if I wanted my JSON to be like below:

{ 
    "rows":[
        {"OrderID":"10248","OrderDate":"1996-07-04","CustomerID":"WILMK","ShipName":"Vins et alcools Chevalier","Freight":"32.3800"},       
        {"OrderID":"10276","OrderDate":"1996-08-08","CustomerID":"TORTU","ShipName":"Tortuga Restaurante","Freight":"13.8400"},
        {"OrderID":"10277","OrderDate":"1996-08-09","CustomerID":"MORGK","ShipName":"Morgenstern Gesundkost","Freight":"125.7700"}
    ]
}

Any advice or reference links is highly appreciated.

Upvotes: 1

Views: 97

Answers (1)

xxfelixxx
xxfelixxx

Reputation: 6592

Create the data structure you are looking for, and then call JSON->encode

In your main package, try the following:

use JSON;

my $JSON  = JSON->new->utf8;
$JSON->convert_blessed(1);

my $data = { rows => [] };
push @{$data->{rows}}, new Emp( "10248", "1996-07-04", "WILMK","Vins","32");
push @{$data->{rows}}, new Emp( "10276", "1996-08-08", "TORTU","Tortuga","13");
push @{$data->{rows}}, new Emp( "10277", "1996-08-09", "MORGK","Morgenstern","125");

$json = $JSON->encode($data);
print "$json\n";

Output:

{"rows":[{"Freight":"32","OrderDate":"1996-07-04","CustomerID":"WILMK","OrderID":"10248","ShipName":"Vins"},
{"Freight":"13","OrderDate":"1996-08-08","CustomerID":"TORTU","OrderID":"10276","ShipName":"Tortuga"},
{"Freight":"125","OrderDate":"1996-08-09","CustomerID":"MORGK","OrderID":"10277","ShipName":"Morgenstern"}]}

Upvotes: 3

Related Questions