How to parse a key - value based dictionary using Perl

♀尐吖头ヾ 提交于 2019-12-11 14:53:41

问题


using Perl I get a key - value based dictionary from an API call.

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"]}

how can I parse it to get the results as bellow?

name : jack
hist friend list :
james
sam
Michael
charlie

Thanks!


回答1:


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";
}



回答2:


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


my $href  = decode_json($content);

use Data::Dumper; print Dumper $href;



回答3:


use JSON::Tiny 'j';

my $data = j $content;

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


来源:https://stackoverflow.com/questions/19923585/how-to-parse-a-key-value-based-dictionary-using-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!