如何使用Perl解析基于键值的字典

1u4esq0p  于 2023-08-06  发布在  Perl
关注(0)|答案(3)|浏览(110)

使用Perl,我从API调用中获得了一个基于key-value的字典。

use strict;
use warnings;

use LWP::Simple;
my $url = "http://example.com/?id=124341";
my $content = get($url);
$content =~ s/ /%20/g;
print $content;

{"id":"85710","name":"jack","friends":["james","sam","Michael","charlie"]}

字符串
我如何解析它以得到如下结果?

name : jack
hist friend list :
james
sam
Michael
charlie

rmbxnbpk

rmbxnbpk1#

use strict;
use warnings;
use JSON 'decode_json';

my $content = '{"id":"85710","name":"jack","friends":["james","sam","Michael","charlie"]}';

my $person = decode_json($content);
print "name : $person->{'name'}\n";
print "his friend list :\n";
for my $friend ( @{ $person->{'friends'} } ) {
    print "$friend\n";
}

字符串

tuwxkamq

tuwxkamq2#

use JSON; # imports encode_json, decode_json, to_json and from_json.

my $href  = decode_json($content);

use Data::Dumper; print Dumper $href;

字符串

lymnna71

lymnna713#

use JSON::Tiny 'j';

my $data = j $content;

printf <<TEMPLATE, $data->{name}, join( "\n", @{ $data->{friends} } );
name : %s
his friend list:
%s
TEMPLATE

字符串

相关问题