在Perl中将数组添加到JSON结构中

时间:2018-12-04 08:25:15

标签: perl

我有一个哈希,看起来如下(在Perl中):

'multi' => {
           'key2' => '123',
           'key1' => 'abc',
           'key3' => 'xwz'
         }

我还具有以下结构:

my $json_struct = {
    name => $name,
    time => $time,
};

我想将multi作为具有键和值的数组插入$json_struct中。 我使用$json_struct来将其转换为JSON文件,因此JSON输出应如下所示:

{
    "name" : "some_name",
    "time" : "time",
    "multi" : [ 
    {
        "key" : "key1",
        "value" : "abc"
    }, 
    {
        "key" : "key2",
        "value" : "123"
    },
    {
        "key" : "key3",
        "value" : "xwz"
    }
],
}

我该怎么办?什么是最干净的方法(不导入其他模块)。

2 个答案:

答案 0 :(得分:1)

要添加数组,只需将对数组的引用添加到数据结构中:

$json_struct->{multi} = \@multi;

如果%multi是哈希,则可以使用:

my @multi = map { +{ key => $_, value => $multi{ $_ } } } sort keys %multi;
$json_struct->{multi} = \@multi;

另请参见

https://perldoc.perl.org/perlreftut.html

答案 1 :(得分:0)

#!/usr/bin/env perl
use v5.10.1;
use warnings FATAL => "all";
use autodie;
use Data::Dumper;

my $payload = {
    'multi' => {
        'key2' => '123',
        'key1' => 'abc',
        'key3' => 'xwz'
    }
};

my $json_struct = {
    name => "foo",
    time => "2018-12-03",
};

for my $key (keys %$payload) {
    my @as_array = map { 
        { 
            key => $_, 
            value => $payload->{$key}{$_} 
        } 
    } keys %{$payload->{$key}};
    $json_struct->{$key} = \@as_array;
}

say Dumper $json_struct;

# $VAR1 = {
#     'name' => 'foo',
#     'time' => '2018-12-03',
#     'multi' => [
#         {
#             'value' => 'abc',
#             'key' => 'key1'
#         },
#         {
#             'value' => '123',
#             'key' => 'key2'
#         },
#         {
#             'key' => 'key3',
#             'value' => 'xwz'
#         }
#     ]
# };