1

我有一个打印的 JSON

{"d":{"success":true,"drivers":[{"FIRST_NAME":"JOHN","LAST_NAME":"SMITH"},{"FIRST_NAME":"JANE","LAST_NAME":"DOE"}]}}

名称会根据在数据库中找到的内容而变化。对于 JSON 中返回的每个结果,我需要以这种格式推送:

push(@$dummy_data, {'name' => 'testname', 'key' => 'somekey-1234'});
push(@$dummy_data, {'name' => 'testname2', 'key' => 'somekey-5678'});

所以对于这个例子,它将是 John Smith 代替 testname 和 Jane 代替 testname2 我将如何为 json 中的每个名字和姓氏以上述格式推送?

4

1 回答 1

1

让我们试试这个新游戏

use strict; use warnings;
use JSON::XS;
use Data::Dumper;

# creating reference to a void ARRAY
my $dummy_data = [];

# creating $json string
my $json = '{"d":{"success":true,"drivers":[{"FIRST_NAME":"JOHN","LAST_NAME":"SMITH"},{"FIRST_NAME":"JANE","LAST_NAME":"DOE"}]}}';

# converting JSON -> Perl data structure
my $perl_hash = decode_json $json;

# feeding $dummy_data ARRAY ref with a HASH
push @$dummy_data, {
    name => $perl_hash->{d}->{drivers}->[0]->{FIRST_NAME},
    key => $perl_hash->{d}->{drivers}->[1]->{FIRST_NAME}
};

# print what we have finally
print Dumper $dummy_data;

输出

$VAR1 = [
          {
            'name' => 'JOHN',
            'key' => 'JANE'
          }
        ];
于 2013-02-20T16:32:32.953 回答