将Perl字符串转换为Json

将Perl字符串转换为Json,json,perl,Json,Perl,我尝试使用上述示例将我的字符串转换为JSON。输出如下所示: package Emp; sub new { my $class = shift; my $self = { OrderID => shift, OrderDate => shift, CustomerID => shift, ShipName => shift, Freight => shift,

我尝试使用上述示例将我的
字符串
转换为
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";    
{"Freight":"10","OrderDate":"1996-07-04","CustomerID":"WILMK","OrderID":"10248","ShipName":"Vins"}
如果我希望我的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";    
{"Freight":"10","OrderDate":"1996-07-04","CustomerID":"WILMK","OrderID":"10248","ShipName":"Vins"}

非常感谢您提供任何建议或参考链接。

创建您要查找的数据结构,然后调用JSON->encode

在主程序包中,尝试以下操作:

{ 
    "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"}
    ]
}
输出:

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";