【问题标题】:How to create key value JSON response in perl script with MYSQL data如何使用 MYSQL 数据在 perl 脚本中创建键值 JSON 响应
【发布时间】:2015-05-24 15:00:23
【问题描述】:

我有一个 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 脚本中进行哪些更改? 请帮忙。

【问题讨论】:

    标签: mysql json perl


    【解决方案1】:

    如果您特别不需要遍历每一行,我更喜欢使用 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;
    

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

    【讨论】:

      【解决方案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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-29
        • 2015-09-24
        • 1970-01-01
        • 2022-11-12
        • 2019-08-01
        • 2016-08-18
        • 2018-04-25
        相关资源
        最近更新 更多