【问题标题】:How to parse a key - value based dictionary using Perl如何使用 Perl 解析基于键值的字典
【发布时间】:2013-11-12 07:46:13
【问题描述】:

使用 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

谢谢!

【问题讨论】:

    标签: perl api dictionary hashmap fetch


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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-28
          相关资源
          最近更新 更多