如何使用MYSQL数据在perl脚本中创建键值JSON响应

时间:2015-03-21 05:06:24

标签: mysql json perl

我有一个perl脚本,它以JSON格式执行一些查询和返回响应。但返回JSON只是值数组。

这是Perl脚本

my $sql_query = "SELECT * from table_categories";
my $statement = $db_handle->prepare ($sql_query) or die "Couldn't prepare query '$sql_query': $DBI::errstr\n";  
$statement->execute() or die "SQL Error: $DBI::errstr\n";  

my @loop_data = ();

while (my @data = $statement->fetchrow_array())
{
    push(@loop_data, @data);
}   

my $json;
$json->{"entries"} = \@loop_data;

my $json_text = to_json($json);
print $json_text;

并且响应就像这样

{
    "entries": [
        [
            "1",
            "Salt and Sugar",
            "/images/salt_sugar.png",
            "7"
        ],
        [
            "2",
            "Tea and Coffee",
            "/images/tea_and_coffee.png",
            "6"
        ],
        [
            "3",
            "Spice and Pickles",
            "/images/categories/spice_pickles.png",
            "7"
        ],
        [
            "4",
            "Pooja Needs",
            "/images/categories/pooja-needs.png",
            "9"
        ],
        [
            "5",
            "Dry Fruits",
            "/images/categories/dry_fruits.png",
            "7"
        ]
    ]
}

但我想要这样的回答:

{
"entries": [
    [
        "id": "1",
        "name": "Salt and Sugar",
        "image": "/images/salt_sugar.png",
        "rank": "7"
    ],
    [
        "id": "2",
        "name": "Tea and Coffee",
        "image": "/images/tea_and_coffee.png",
        "rank": "6"
    ]
]
}

如何实现? 我需要在PERL脚本中做些什么改变? 请帮忙。

2 个答案:

答案 0 :(得分:4)

如果您特别不需要遍历每一行,我宁愿使用selectall_arrayref进行切片:

my $json;
my $sql_query = "SELECT * FROM table_categories";
$json->{entries} = $db_handle->selectall_arrayref( $sql_query, {Slice => {} } );

my $json_text = to_json($json);
print $json_text;

因此,您也可以获得密钥,代码更紧凑,更清晰。

答案 1 :(得分:2)

您可以使用fetchrow_hashref代替fetchrow_array来接收hashref,其中使用以下代码将列名用于属性名称。

my @loop_data = ();

while (my $hashref = $statement->fetchrow_hashref())
{
    push(@loop_data,$hashref);
}

更多信息:https://metacpan.org/pod/DBI#fetchrow_hashref