【问题标题】:decode list of JSON objects to array of hashes in perl将 JSON 对象列表解码为 perl 中的哈希数组
【发布时间】:2016-08-19 04:09:18
【问题描述】:

我是 Perl 的新手,我想将下面的 JSON 解析成哈希数组,(优先使用 map 方法)

[
    {   "name" : "Theodor Nelson",
        "id": "_333301",
        "address": "Hello_world"
    },
    {   "name": "Morton Heilig",
        "id": "_13204",
        "address": "Welcome"
     }
    ]

然后只想打印“

名字

身份证

在 foreach 循环中的值。 任何形式的帮助将不胜感激。

【问题讨论】:

  • 您应该查看JSON::XS 模块。有很多例子可以准确地描述你想要做什么。 my $aref = decode_json($str); print "$_->{id}: $_->{name}\n" for @$aref;
  • 你能告诉我如何打印视图文件中的值吗?
  • 我不明白你在问什么。
  • 我的意思是如果我将上述哈希数组传递到视图文件 (.tt) 文件中,那么我如何使用 /get 值在字段中显示它
  • 你需要edit你的问题来包含一些代码。

标签: arrays json perl


【解决方案1】:
use JSON qw(from_json);

# The JSON module likes to die on errors
my $json_data = eval { return from_json($json); };
die "$@ while reading JSON" if $@; # Replace by your error handling
die "JSON top level is no array" unless ref($json_data) eq 'ARRAY'; # Replace by your error handling

for my $hashref (@{$json_data}) {
    print $hashref->{name}."\n";
    print $hashref->{id}."\n";
}

错误处理显然是可选的,具体取决于您的用例。一次性或手动脚本可能会死掉,而生产级脚本应该有适当的错误处理。

JSON 模块是JSON::PPJSON::XS 的包装器。它选择本地系统上可用的模块。 JSON::XS 更快,但可能没有安装。 JSON::PP 是纯 Perl(没有外部 C/C++ 库)并且是 Perl 核心的一部分。

fordereferences the Array-reference 代表您的顶级 JSON 数组。每个项目都应该是一个哈希引用。按照链接了解有关每个主题的更多信息。

【讨论】:

    【解决方案2】:

    你可以简单地做喜欢

    use JSON qw(encode_json decode_json);
    
    my $JSON = [{   "name" : "Theodor Nelson",
            "id": "_333301",
            "address": "Hello_world },
            {   "name": "Morton Heilig",
            "id": "_13204",
            "address": "Welcome"}]
    
    my $decoded = decode_json $JSON;
    
    return template 'yourtemplate', {
        options =>  $decoded,
            ..,
            ..}
    

    在视图文件中,您可以使用 option.idoption.nameoption.address 或 FOREACH 循环中所需的任何内容访问它。

    【讨论】:

      【解决方案3】:
      use JSON::XS qw( decode_json );
      
      my $data = decode_json($json);
      
      $template->process(..., { data => $data }, ...)
         or die(...);
      

      模板:

      [% FOREACH rec IN data %]
         [% rec.id %]: [% rec.name %]
      [% END %]
      

      【讨论】:

        猜你喜欢
        • 2017-09-25
        • 2020-10-29
        • 2016-07-25
        • 1970-01-01
        • 2015-08-25
        • 2016-01-28
        • 2017-12-23
        • 2014-04-27
        • 2013-06-28
        相关资源
        最近更新 更多