【问题标题】:Creating a JSON array containing multiple variables创建包含多个变量的 JSON 数组
【发布时间】:2021-01-27 07:01:54
【问题描述】:

我想修改我的 Perl 脚本以使用 json_encode 函数输出变量列表,但我不确定如何。

这是我未修改的 Perl 脚本的输出:

Vicia_sativa = Vicia_sativa.png 
Geranium_maculatum = Geranium_maculatum.png 
Narcissus_pseudonarcissus = Narcissus_pseudonarcissus1.png Narcissus_pseudonarcissus2.png 
Polygonum_persicaria = Polygonum_persicaria1.png Polygonum_persicaria2.png 
Corylus_americana = Corylus_americana1.png Corylus_americana2.png

等号左边的变量是植物名称,等号右边的一个或多个文件名是植物照片。请注意,这些文件名没有用逗号分隔。

这是生成上述输出的 Perl 脚本:

#!/usr/bin/perl
use strict;
use warnings;
use English;   ## use names rather than symbols for special variables

my $dir = '/Users/jdm/Desktop/xampp/htdocs/cnc/images/plants';

opendir my $dfh, $dir  or die "Can't open $dir: $OS_ERROR";
my %genus_species;  ## store matching entries in a hash

for my $file (readdir $dfh)
{
    next unless $file =~ /.png$/;  ## entry must have .png extension
    my $genus = $file =~ s/\d*\.png$//r;
    push(@{$genus_species{$genus}}, $file);   ## push to array,the @{} is to cast the single entry to a reference to an list
}

for my $genus (keys %genus_species)
{
    print "$genus = ";
    print "$_ " for sort @{$genus_species{$genus}}; # sort and loop though entries in list reference
    print "\n";
}

请告知如何在 JSON 数组中输出这些变量。谢谢。

更新...这是修订后的脚本,其中包含每个论坛成员的建议更改:

#!/usr/bin/perl
use strict;
use warnings;

use JSON::PP;

use English;   ## use names rather than symbols for special variables

my $dir = '/Users/jdm/Desktop/xampp/htdocs/cnc/images/plants';

opendir my $dfh, $dir  or die "Can't open $dir: $OS_ERROR";
my %genus_species;  ## store matching entries in a hash

for my $file (readdir $dfh)
{
    next unless $file =~ /.png$/;  ## entry must have .png extension
    my $genus = $file =~ s/\d*\.png$//r;
    push(@{$genus_species{$genus}}, $file);   ## push to array,the @{} is to cast the single entry to a reference to an list
}

print(encode_json(\%genus_species));

修改后的代码有效!但是,文件名不再排序。任何想法如何将 sort 合并到 encode_json 函数中?

【问题讨论】:

  • 使用模块,例如Cpanel::JSON::XS
  • 感谢您的见解,但我不知道如何“使用模块”。

标签: arrays json perl


【解决方案1】:

实际上非常简单...您可以使用JSON::PP module 并将您的哈希引用传递给encode_json()

#!/usr/bin/perl

use strict;
use warnings;

use JSON::PP;
# your other code goes here...

# instead of `for my $genus (keys %genus_species) { ... }` do:
print(encode_json(\%genus_species));

【讨论】:

  • 好的,我尝试了代码并得到了错误:无标题文本 55:5:无法在 @INC 中找到 JSON.pm(您可能需要安装 JSON 模块)。但是,今天早些时候,我确认我的 Mac 上确实安装了 JSON::PP 模块。不知道现在该怎么办!
  • @Jeff:JSON:PP 的工作方式相同。查看编辑。
  • 好的...插入 JSON::PP;现在我得到第 23 和 24 行语法错误,指的是: print "$genus = "; print "$_ " for sort @{$genus_species{$genus}};.... 错误显示:全局符号 "$genus" 需要显式包。
  • 好的...删除以下所有内容: print(encode_json(\%genus_species));现在没有错误,但只输出一个变量。不知道为什么……请指教。谢谢。
  • @Jeff:您是否对创建哈希的方式进行了任何更改?它应该将整个内容输出为 JSON。如果缺少某些东西,它已经在散列中丢失了。
猜你喜欢
  • 2010-11-25
  • 2020-02-26
  • 2013-02-01
  • 1970-01-01
  • 2021-09-22
  • 2023-03-05
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
相关资源
最近更新 更多